`

Java语法(三)JVM Spec(2) Concepts

 
阅读更多

摘自The JavaTM Virtual Machine Specification

 

 

jconsole.exe自带的工具

at compile time at run time

 

2 Java Concepts 

This book describes Version 1.0.2 of the Java Virtual Machine

This book specifies an abstract machine. It does not document any particular implementation of the Java Virtual Machine, including Sun's. 

The Java Virtual Machine is an abstract design

The original Java Virtual Machine was designed by James Gosling in 1992.         

The Java Virtual Machine is an abstract computing machine. Like a real computing machine, it has an instruction set and uses various memory areas.

The Java Virtual Machine knows nothing of the Java programming language, only of a particular file format, the class file format. A class file contains Java Virtual Machine instructions (or bytecodes) and a symbol table, as well as other ancillary information.

 

2.1 Unicode 

        Except for(除了) comments and identifiers (§2.2) and the contents of character and string literals (§2.3), all input elements in a Java program are formed from only ASCII characters.

 

2.4 Types and Values 

        Java is a strongly typed language, which means that every variable and every expression has a type that is known at compile time.

        The types of the Java language are divided into two categories: primitive types  and reference types 

        Primitive values do not share state with other primitive values

        There are three kinds of reference types: the class types , the interface types , and the array types. 

 

2.5 Variables

        A variable is a storage location. It has an associated type, sometimes called its compile-time type

        There are seven kinds of variables:

                1、A class variable is a field of a class type declared using the keyword static within a class declaration, or with or without the keyword static in an interface declaration.

                 Class variables are created when the class or interface is loaded and are initialized on creation to default values.(引用类型变量初始化值为null)

                2、An instance variable is a field declared within a class declaration.an instance variable  is created and initialized to a default value (§2.5.1) as part of each newly created object of class T or of any class that is a subclass of T. 

                3、Array components are unnamed variables that are created and initialized to default values (§2.5.1) whenever a new object that is an array is created .

                4、Method parameters name argument values passed to a method. a new parameter variable is created each time that method is invoked. The new variable is initialized with the corresponding argument value from the method invocation. 

                5、Constructor parameters name argument values passed to a constructor. 类似method parameters

                6、An exception-handler parameter variable is created each time an exception is caught by a catch clause of a try statement. The new variable is initialized with the actual object associated with the exception 。

                7、Local variables are declared by local variable declaration statements. 本地局部变量.A local variable must be explicitly given a value before it is used。因为它没有其他途径赋值,比如没有get方法。

 

                共7中变量,2种大类型type,4种小类型。

                        Every variable in a Java program must have a value before it is used: 

                        An object is said to be an instance of its class and of all superclasses of its class. Sometimes the class of an object is called its "runtime type(is a compile-time notion)

                        The type of a variable is always declared, and the type of an expression can be deduced at compile time

                        Every array also has a class. The classes for arrays have strange names that are not valid Java identifiers; for example, the class for an array of int components has the name "[I".

 

2.6 Conversions and Promotions

        Identity Conversions(同类转换,其他类型转换的基石)

 

 

2.7 Names and Packages

        Names are used to refer to entities declared in a Java program. A declared entity is a package, type, member (field or method) of a type, parameter, or local variable. 

        The members of a class type (§2.8) are fields (§2.9) and methods (§2.10).

 

2.8 Classes

        A class declaration may include class modifiers(修饰符). A class may be declared public, as discussed in §2.7.8. 

 

2.9 Fields

        The variables of a class type are its fields. Class (static) variables exist once per class. Instance variables exist once per instance of the class.

        Variables may be marked transient to indicate that they are not part of the persistent state of an object

        If the declaration is for a class variable (that is, a static field), then the variable initializer is evaluated and the assignment performed exactly once, when the class is initialized (§2.16.4). 

 

2.10 Methods

        A class inherits from its direct superclass (§2.8.3) and any direct superinterfaces (§2.13.2) all the accessible methods of the superclass and superinterfaces

        Signature是由方法的参数和返回值的类型共同构成的,可以通过javap -s -p ok.T获取

                public static void main(java.lang.String[]);

                Signature: ([Ljava/lang/String;)V                //V返回类型void

                static java.lang.String testAdd(java.lang.String, java.lang.String);

                Signature: (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;

        java中,只有返回类型不同的方法,视为同一方法。

        A method that is declared static is called a class method

        A method that is declared static is called a class method

 

2.12 Constructors

        Constructor declarations are not members. They are never inherited and therefore(因此) are not subject to hiding or overriding.

        If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

 

2.13 Interfaces

        Object类没有实现任何接口,There is no analogue of the class Object for interfaces; that is, while every class is an extension of class Object, there is no single interface of which all interfaces are extensions.

 

2.14 Arrays

        Java arrays are objects, are dynamically created.An array object contains a number of variables.

        The variables contained in an array have no names; instead they are referenced by array access expressions that use non-negative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array.

        All the components of an array have the same type, called the component type of the array. If the component type of an array is T, then the type of the array itself is written T[]. 

        Declaring a variable of array type does not create an array object or allocate any space for array components. It creates only the variable itself, which can contain a reference to an array. 

        Once an array object is created, its length never changes.

 

2.15 Exceptions

        When an exception is thrown, control is transferred from the code that caused the exception to the nearest dynamically enclosing catch clause of a try statement that handles the exception. 

        Java programs can also throw exceptions explicitly, using throw statements. This provides an alternative to the old-fashioned style of handling error conditions by returning distinguished error values, such as the integer value -1, where a negative value would not normally be expected.

        ThreadGroup 

 

        Asynchronous exceptions are rare in Java. They occur only as a result of:

                An invocation of the stop methods of class Thread or ThreadGroup. 

                An InternalError in the Java Virtual Machine.

 

        Error extends Throwable;Exception extends Throwable

        virtual machine errors:

                InternalError: An internal error has occurred in a Java Virtual Machine, because of a fault in the software implementing the virtual machine, a fault in the underlying host system software, or a fault in the hardware. This error is delivered asynchronously when it is detected and may occur at any point in a Java program. 

                OutOfMemoryError: A Java Virtual Machine has run out of either virtual or physical memory, and the automatic storage manager was unable to reclaim enough memory to satisfy an object creation request. 

                StackOverflowError: A Java Virtual Machine has run out of stack space for a thread, typically because the thread is doing an unbounded number of recursive invocations as a result of a fault in the executing program. 

                UnknownError: An exception or error has occurred but, for some reason, a Java Virtual Machine is unable to report the actual exception or error. 

 

2.16 Execution

2.16.1 Virtual Machine Start-up

        It specifies the detailed procedures used in starting up the virtual machine (§2.16.1), class and interface type loading (§2.16.2), linking (§2.16.3), and initialization (§2.16.4).

        A Java Virtual Machine starts execution by invoking the method main of some specified class.

        The virtual machine then uses a ClassLoader (§2.16.2) to attempt to find such a binary representation. 

        After Terminator is loaded, it must be initialized before main can be invoked and a type (class or interface) must always be linked before it is initialized. Linking involves verification, preparation, and (optionally) resolution.        

        Verification checks that the loaded representation of Terminator is well formed, with a proper symbol table.

        Preparation involves allocation of static storage and any data structures that are used internally by the virtual machine, such as method tables.

        Resolution is the process of checking symbolic references from Terminator to other classes and interfaces, by loading the other classes and interfaces that are mentioned and checking that the references are correct.

        The resolution step is optional at the time of initial linkage.

        Initialization consists of execution of any class variable initializers and static initializers of the class Terminator, in textual order. But before Terminator can be initialized, its direct superclass must be initialized, as well as the direct superclass of its direct superclass, and so on, recursively. In the simplest case, Terminator has Object as its implicit direct superclass; if class Object has not yet been initialized, then it must be initialized before Terminator is initialized.

 

2.16.2 Loading 

        Loading refers to the process of finding the binary form of a class or interface type with a particular name

        The loading process is implemented by the class ClassLoader and its subclasses. Different subclasses of ClassLoader may implement different loading policies. In particular, a class loader may cache binary representations of classes and interfaces, prefetch them based on expected usage, or load a group of related classes together. 

        If an error occurs during class loading, then an instance of one of the following subclasses of class LinkageError will be thrown at any point in the Java program that (directly or indirectly) uses the type:

                ClassCircularityError: A class or interface could not be loaded because it would be its own superclass or superinterface (§2.13.2). 

                ClassFormatError: The binary data that purports to specify a requested compiled class or interface is malformed. 

                NoClassDefFoundError: No definition for a requested class or interface could be found by the relevant class loader. 

 

2.16.3 Linking: Verification, Preparation, and Resolution

        Linking is the process of taking a binary form of a class or interface type and combining it into the runtime state of the Java Virtual Machine, so that it can be executed.

        Verification:

        Verification ensures that the binary representation of a class or interface is structurally correct. 

        Preparation:

        Preparation involves creating the static fields for a class or interface and initializing such fields to the standard default values (§2.5.1). This does not require the execution of any Java code; explicit initializers for static fields are executed as part of initialization (§2.16.4), not preparation.

        AbstractMethodError: A class that is not declared to be abstract has an abstract method。

        One particularly useful data structure is a "method table" or other data structure that allows any method to be invoked on instances of a class without requiring a search of superclasses at invocation time.

        Resolution:

        IllegalAccessError:if a field that is originally declared public is changed to be private after another class that refers to the field has been compiled(访问权限被其他类修改了). 

        InstantiationError: if a class that is originally not abstract is changed to be abstract after another class that refers to the class in question has been compiled. 

        NoSuchFieldError: if a field declaration was deleted from a class after another class that refers to the field was compiled. 

        NoSuchMethodError:if a method declaration was deleted from a class after another class that refers to the method was compiled 

 

2.16.4 Initialization

        Initialization of a class consists of executing its static initializers (§2.11) and the initializers for static fields (§2.9.2) declared in the class. Initialization of an interface consists of executing the initializers for fields declared in the interface (§2.13.4). 

        Before a class is initialized, its superclass must be initialized, but interfaces implemented by the class need not be initialized.

        A class or interface type T will be initialized at its first active(主动) use, which occurs if:

                T is a class and a method actually declared in T (rather than inherited from a superclass) is invoked. 

                T is a class and a constructor for class T is invoked. 

                怎么理解???A nonconstant field declared in T (rather than inherited from a superclass or superinterface) is used or assigned. A constant field is one that is (explicitly or implicitly) both final and static, and that is initialized with the value of a compile-time constant expression. Java specifies that a reference to such a field must be resolved at compile time to a copy of the compile-time constant value, so uses of such field are never active uses. 

        All other uses of a type are passive(被动) uses. 

 

2.16.5 Detailed Initialization Procedure

        Because Java is multithreaded, initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time. 

        The implementation of the Java Virtual Machine is responsible for taking care of synchronization and recursive initialization by using the following procedure. 

        The procedure for initializing a class or interface,需要synchronized,因为是多线程的。

        if the Class object represents a class rather than an interface, and the superclass of this class has not yet been initialized, then recursively perform this entire procedure for the superclass. If necessary, verify and prepare the superclass first.

        execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block, except that final static variables and fields of interfaces whose values are compile-time constants are initialized first(static final的是在编译.class时已经初始化过了,用javap -c 查看)

 

2.16.6 Creation of New Class Instances

        Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden. If there is not sufficient space available to allocate memory for the object, then creation of the class instance completes abruptly with an OutOfMemoryError.

 

2.16.7 Finalization of Class Instances

        The class Object has a protected method called finalize。

        Before the storage for an object is reclaimed by the garbage collector, the Java Virtual Machine will invoke the finalizer of that object. 

        The Java language does not specify how soon a finalizer will be invoked, except to say that it will happen before the storage for the object is reused.

        Also, the Java language does not specify which thread will invoke the finalizer for any given object. 

        Unlike constructors, finalizers do not automatically invoke the finalizer for the superclass; such an invocation must be coded explicitly.

 

2.16.8 Finalization and Unloading of Classes and Interfaces

        A class may not be unloaded while any instance of it is still reachable.

 

2.16.9 Virtual Machine Exit

        A Java Virtual Machine terminates all its activity and exits when one of two things happens: 

                All the threads that are not daemon threads (§2.17) terminate. 

                Some thread invokes the exit method of class Runtime or class System and the exit operation is permitted by the security manager. 

 

2.17 Threads

        While most of the preceding discussion is concerned only with the behavior of Java code as executed by a single thread,each Java Virtual Machine can support many threads of execution at once. 

        These threads independently execute Java code that operates on Java values and objects residing in a shared main memory.                                                                                                        

        The Java Virtual Machine initially starts up with a single non-daemon thread which typically calls the method main of some class. The virtual machine may also create other daemon threads for internal purposes. The Java Virtual Machine exits when all non-daemon threads have died 

        To synchronize threads, Java uses monitors, which are a high-level mechanism for allowing only one thread at a time to execute a region of code protected by the monitor. The behavior of monitors is explained in terms of locks. There is a lock associated with each object.

        The methods wait, notify, and notifyAll of class Object support an efficient transfer of control from one thread to another. 

        a thread can suspend itself using wait until such time as another thread awakens it using notify or notifyAll.

        If two or more concurrent(并发) threads act on a shared variable, there is a possibility that the actions on the variable will produce timing-dependent results. This dependence on timing is inherent(内在的) in concurrent programming.

        Each thread has a working memory, in which it may keep copies of the values of variables from the main memory that are shared between all threads. To access a shared variable, a thread usually first obtains a lock and flushes its working memory. This guarantees that shared values will thereafter be loaded from the shared main memory to the working memory of the thread. By unlocking a lock, a thread guarantees that the values held by the thread in its working memory will be written back to the main memory.

         Java的内存模型JMM(Java Memory Model)JMM主要是为了规定了线程和内存之间的一些关系。根据JMM的设计,系统存在一个主内存(Main Memory),Java中所有实例变量都储存在主存中,对于所有线程都是共享的。每条线程都有自己的工作内存(Working Memory),工作内存由缓存和堆栈两部分组成,缓存中保存的是主存中变量的拷贝,缓存可能并不总和主存同步,也就是缓存中变量的修改可能没有立刻写到主存中;堆栈中保存的是线程的局部变量,线程之间无法相互直接访问堆栈中的变量。

 
分享到:
评论

相关推荐

    揭秘Java虚拟机-JVM设计原理与实现

    《揭秘Java虚拟机-JVM设计原理与实现》这本书深入探讨了Java虚拟机(JVM)的工作原理及其在Java编程中的核心地位。Java虚拟机是Java平台的核心组成部分,它负责执行字节码,为开发者提供了跨平台的运行环境。以下是...

    java11-jvm白皮书

    Java 11 JVM 白皮书是一份详细阐述Java虚拟机(JVM)在Java 11版本中的特性和优化的文档。这份白皮书主要关注JVM的内部工作原理,包括垃圾收集、内存管理、类加载机制、性能优化等方面,是Java开发者深入理解Java...

    jvmjava,java实现的JVM。.zip

    《Java实现的JVM——深入理解与实践》 在计算机科学领域,Java虚拟机(JVM)是Java语言的关键组成部分,它使得Java程序能够在不同平台上运行而无需重新编译。本项目“jvmjava”是一个开源项目,由Java语言实现,...

    实战Java虚拟机——JVM故障诊断与性能优化 pdf

    《实战Java虚拟机——JVM故障诊断与性能优化》内容简介:随着越来越多的第三方语言(Groovy、Scala、JRuby等)在Java虚拟机上运行,Java也俨然成为一个充满活力的生态圈。本书将通过200余示例详细介绍Java虚拟机中的...

    JAVA虚拟机(JVM)规范(中文版).rar

    JAVA虚拟机(JVM)是Java语言的核心组成部分,它为Java程序提供了运行环境,使得Java代码能在任何支持JVM的平台上运行,实现了“一次编写,到处运行”的目标。JVM规范定义了Java程序如何在特定系统上被加载、解析、...

    Java Jar JVM Exe

    Java Jar JVM Exe 可执行文件 Java Jar JVM Exe 可执行文件 Java Jar JVM Exe 可执行文件 Java Jar JVM Exe 可执行文件 Java Jar JVM Exe 可执行文件

    java虚拟机JVM详解ppt

    ### Java虚拟机(JVM)详解 #### 一、引言 Java虚拟机(JVM)作为Java编程语言的核心组件之一,其重要性不言而喻。本文将深入剖析JVM的基本概念、架构及其内存管理机制,重点解读堆和栈内存溢出的情况及案例分析。 ##...

    深入理解Java虚拟机JVM高级特性与最佳实践1

    《深入理解Java虚拟机JVM高级特性与最佳实践》是一本专注于Java开发人员提升技术水平的著作,由周志明撰写。这本书旨在填补Java技术体系中关于Java虚拟机(JVM)知识的空白,帮助读者深入理解JVM的工作原理及其对...

    深入理解Java虚拟机(jvm性能调优+内存模型+虚拟机原理).zip

    《深入理解Java虚拟机》是一本深度探讨Java虚拟机(JVM)的著作,涵盖了JVM性能调优、内存模型以及虚拟机原理等多个关键领域。本文将基于这些主题,详细阐述其中的重要知识点。 首先,我们要了解Java虚拟机(JVM)...

    java11-jvm白皮书_java_govwe_

    JVM(Java虚拟机)是Java平台的核心组件,负责运行Java程序。在Java 11中,对JVM进行了一些关键的优化和更新,这些变化对于理解和提升Java应用程序的效率至关重要。 首先,让我们深入了解Java 11中的JVM改进。JVM...

    JVM Spec PDF

    JVM Spec PDF,即Java虚拟机规范,是官方提供的详细文档,用于解释JVM的工作原理、内存模型、类加载机制、垃圾收集以及如何执行Java代码等核心概念。这份文档对于Java开发者来说具有极高的学习价值,尤其是对于想要...

    实战Java虚拟机——JVM故障诊断与性能优化

    《实战Java虚拟机——JVM故障诊断与性能优化》是一本深入探讨Java开发人员和运维人员必备技能的书籍。本书作者葛一鸣以其丰富的实战经验,详细阐述了JVM(Java Virtual Machine)的工作原理,以及如何有效地进行故障...

    实战Java虚拟机——JVM故障诊断与性能优化.pdf

    《实战Java虚拟机——JVM故障诊断与性能优化》是一本深入探讨Java开发中的关键环节——Java虚拟机(JVM)的专著。本书聚焦于实际应用中的问题解决和性能调优,对于Java开发者和系统管理员来说,是提升技术水平的重要...

    java基础之JVM

    ### Java基础之JVM #### 一、JVM简介 **1.1 JVM是什么** Java Virtual Machine (JVM),即Java虚拟机,是Java技术的核心组成部分之一。它是一种抽象计算机,能够执行Java字节码(一种中间代码)的虚拟机环境。JVM...

    jvm规范和java规范

    这两部分规范分别定义了Java程序如何在JVM上运行以及Java编程语言的语法和语义。 《Java语言规范》(Java Language Specification,简称JLS)8版是描述Java编程语言的官方文档。它详细阐述了语言的所有细节,包括...

    Java虚拟机(JVM)面试题 51道.pdf

    Java虚拟机(JVM)是Java语言的核心组成部分,它为Java程序提供了一个跨平台的运行环境。以下是对JVM相关知识点的详细解释: 1. **Java代码的执行过程**: - 开发人员编写的Java代码首先通过`javac`编译器转化为`....

    揭秘Java虚拟机_JVM设计原理与实现.part2

    需要两部分一起解压才可以: 当前为第二部分。 第一部分地址如下: https://download.csdn.net/download/dcxy0/10374640 也可以通过下面的地址找另外第一部分的文件:https://download.csdn.net/user/dcxy0/uploads

    JAVA语法大全(基本语法)

    JAVA程序的运行体系包括Source code、javac、JVM三个部分。其中,javac对源代码进行词法分析和类型校验,生成字节码文件,然后JVM执行字节码文件中的类,並對类进行验证、加载和执行。 关键字是JAVA语言的基本组成...

    java 查看JVM中所有的线程的活动状况

    在Java编程环境中,了解JVM(Java虚拟机)中所有线程的活动状态对于调试多线程程序至关重要。本文将详细讲解如何查看JVM中的线程活动情况,并提供相关示例代码。 首先,Java提供了`java.lang.management....

    实战Java虚拟机_JVM故障诊断与性能优化

    实战Java虚拟机_JVM故障诊断与性能优化 JVM故障诊断与性能优化 JVM调优

Global site tag (gtag.js) - Google Analytics