Class loading mechanism
Class starts from being loaded into the virtual machine's memory, and its entire lifecycle includes: Load (Loading), validate (verification), prepare (preparation), Parse (Resolution), Initialize ( initialization), use (using), and unload (unloading) 7 stages. Where preparation, validation, parsing 3 parts collectively referred to as the connection (linking):
The order of the 5 stages of loading, validating, preparing, initializing, and unloading is determined, and the load process of the class must begin in this order, and the parsing phase is not necessarily: it can be started after the initialization phase in some cases, This is to support runtime bindings for the Java language (also known as dynamic binding or late binding). The following statements are in the context of hotspot.
Loading
During the load phase (you can refer to Java.lang.ClassLoader's LoadClass () method), the virtual machine needs to complete the following 3 things:
- A binary byte stream that defines this class is obtained through the fully qualified name of a class (it is not specified to be obtained from a class file, from other channels, such as: network, dynamic generation, database, etc.);
- Transform the static storage structure represented by this byte stream into the runtime data structure of the method area;
- Generate a Java.lang.Class object representing this class in memory as the access entry for various data of this class in the method area;
Portions of the load phase and connection phase (linking), such as some bytecode file format validation actions, are interleaved, the loading phase is not complete, the connection phase may have begun, but the actions taken during the loading phase of these clips are still part of the connection phase, The start time of the two phases remains in a fixed sequence.
Validation
Validation is the first step in the connection phase, which is designed to ensure that the information contained in the byte stream of a class file conforms to the requirements of the current virtual machine and does not compromise the security of the virtual machine itself.
The validation phase will roughly complete the 4-phase inspection action:
- File Format verification: Verify that the byte stream conforms to the specification of the class file format, for example: whether to start with magic 0xCAFEBABE, whether the primary and secondary version number is within the processing range of the current virtual machine, and whether the constants in the constant pool have unsupported types.
- Meta-data validation: Semantic analysis of the information described in bytecode (note: Comparing the semantic analysis of the JAVAC compilation phase) to ensure that the information it describes conforms to the requirements of the Java language specification, for example: Whether this class has a parent class, except Java.lang.Object.
- Bytecode verification: Through data flow and control flow analysis, it is reasonable to determine that the program semantics are legal and logical.
- Symbol Reference Validation: Ensures that parsing actions are performed correctly.
The validation phase is important, but not necessary, and it has no effect on the program runtime, and if the referenced classes are repeatedly validated, consider using the-xverifynone parameter to turn off most of the class validation measures to shorten the load time of the virtual machine class.
Prepare
The prep phase is a phase that formally allocates memory for class variables and sets the initial value of class variables, and the memory used by these variables is allocated in the method area. The memory allocation at this time includes only class variables (variables that are modified by static), not instance variables, and instance variables are allocated to the heap as objects are instantiated. Second, the initial value referred to here is the 0 value of the data type, assuming that a class variable is defined as:
| 1 |
publicstatic intvalue=123; |
The initial value of the variable value after the prep phase is 0 instead of 123. Since no Java methods have been executed at this time, the putstatic instruction that assigns value 123 is that the program is compiled and stored in the class constructor () method. So an action that assigns value to 123 will not be executed until the initialization stage.
As for "special case" means: public static final int value=123, that is, when the field property of a class field is Constantvalue, it is initialized to the specified value in the preparation phase, so after the label is final, Value is initialized to 123 instead of 0 in the prepare phase.
parsing
The parsing phase is the process by which a virtual machine replaces a symbolic reference within a constant pool with a direct reference. Parsing actions are primarily for classes or interfaces, fields, class methods, interface methods, method types, method handles, and call Point qualifier 7 class symbol references.
Initialize
The class initialization phase is the last step in the class loading process, and in the initialization phase, the Java program code defined in the class is really started. In preparation for extremes, variables have been assigned the initial value of the system requirements by default, while in the initialization phase, the process of executing the class constructor <clinit> () method.
The <clinit> () method is generated by the compiler's automatic collection of assignment actions for all class variables in the class and statements in the static statement block static{}, and the order in which the compilers are collected is determined by the order in which the statements appear in the source file. A static statement block can only access variables that are defined before a static statement block, a variable that is defined after it, and a block of static statements in front of it may be assigned, but cannot be accessed. As follows:
| 123456789 |
public class Test{ static { i=0; System.out.println(i);//这句编译器会报错:Cannot reference a field before it is defined(非法向前应用) } static int i=1;} |
The <clinit> () method differs from the instance constructor <init> () method in that it does not require a display to call the parent class constructor, and the virtual opportunity guarantees that the parent class's <clinit> () before the subclass <init> () method executes The method method has been executed.
Because the <clinit> () method of the parent class executes first, it means that the static statement block defined in the parent class takes precedence over the variable assignment operation of the child class.
The <clinit> () method is not required for a class or interface, and if there is no static statement block in a class, and there is no assignment to the variable, the compiler can not produce the <clinit> () method for this class.
A static statement block cannot be used in an interface, but there are still assignment operations for variable initialization, so the interface will generate the <clinit> () method as the class. However, unlike the class interface, the <clinit> () method of the execution interface does not require the parent interface's <clinit> () method to be executed first. The parent interface is initialized only if the variables defined in the parent interface are used. In addition, the implementation class of the interface does not execute the <clinit> () method of the interface at initialization time.
Virtual opportunity to ensure that a class of <clinit> () method in the multithreaded environment is correctly locking, synchronization, if more than one thread to initialize a class at the same time, then there will only one thread to execute the class of the <clinit> () method, other threads need to block wait, Until the active thread executes the <clinit> () method is complete.
The virtual machine specification strictly stipulates that only 5 of the cases (jdk1.7) must "initialize" the class (while loading, validating, and preparing the natural need to start before this):
- When encountering new,getstatic,putstatic,invokestatic this offset bytecode directive, if the class has not been initialized, it needs to trigger its initialization first. The most common Java code scenario for generating these 4 instructions is when instantiating an object using the New keyword, reading or setting a static field of a class (except for the static field that was final decorated, which has been placed in a constant pool by the compiler), and when invoking a static method of a class.
- When you use the Java.lang.reflect package method to make a reflection call to a class, if the class has not been initialized, you need to trigger its initialization first.
- When initializing a class, it is necessary to trigger the initialization of its parent class if it finds that its parent class has not yet been initialized.
- When the virtual machine starts, the user needs to specify a main class to execute (the class that contains the main () method), and the virtual opportunity initializes the main class first.
- When using jdk1.7 Dynamic language support, if a java.lang.invoke.MethodHandle instance finally resolves the result ref_getstatic,ref_putstatic,ref_invokestatic the method handle, And the class that corresponds to this method handle is not initialized, it needs to be initialized before it is triggered.
The life cycle of a class: load, validate, prepare, initialize, unload in sequence, parsing does not guarantee strict sequential execution, validation can be ignored by parameter configuration to increase the speed of class loading.
The JVM does not specify the timing of the load, but there is an initialization time: When a class object is generated with the new constructor or reflection, when a static variable or method of the class is invoked, when the class has a main function entry when it initializes the subclass of the class. A passive call does not initialize the class: Call the class constant member variable and invoke the parent class static member.
When the JVM initializes a class, it merges its instance variables (member variables), instance code blocks, after the parent class constructor, the constructor code area (the Init function). ), the static member variables and static blocks of code are merged into the <cinit> function when the class is initialized for the first time.
Class variables allocate memory space during the prep phase and perform default operations, and member variables can be initialized up to four times when an object is generated: The prep phase allocates memory space and assigns default values, performs a declaration-time assignment operation, executes an instance code block assignment operation, and executes the assignment operation in the constructor.
Java class loading mechanism