`

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),工作内存由缓存和堆栈两部分组成,缓存中保存的是主存中变量的拷贝,缓存可能并不总和主存同步,也就是缓存中变量的修改可能没有立刻写到主存中;堆栈中保存的是线程的局部变量,线程之间无法相互直接访问堆栈中的变量。

 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics