Jvm class loading mechanism
The life cycle of a class is shown in the following figure. Note that this is only the starting sequence of each stage. It is not a stage that can be started until the execution of the previous stage is complete. Therefore, one stage may be running, and another stage may also start to run.
The Java virtual machine specification does not specify when to load classes, however, it is strictly stipulated that classes must be initialized immediately in the following five cases (loading, verification, preparation, and resolution must be completed before this ):
1. When you use the new keyword to instantiate an object, read or set static fields of a class, or call a method. Note that the final modified constant has been stored in the constant pool during the compilation phase. Therefore, the static final field of a class will not load a class.
2. When calling a class using the reflection method, if the class has not been initialized, it must be initialized first.
3. When calling a class, if the parent class has not been initialized, initialize the parent class first.
4. When a VM is started, you need to create a main class (including the class of the main method) to be executed. The virtual opportunity first initializes the main class.
5. When jdk1.7 is supported in dynamic languages. lang. invoke. the final parsing result of the MethodHandle instance is the method handles of REF_getStatic, REF_putStatic, and REF_invokeStatic. If the class corresponding to this method handle has not been initialized, You need to initialize it first.
The following describes the loading process of classes:
Load
In this phase, the virtual machine must complete the following three tasks:
1. Get the binary byte stream that defines this class using the full qualified name of a class
2. Convert the static storage structure represented by this byte stream into the runtime data structure of the method area.
3. Generate a java. lang. Class Object that represents this Class in the memory, which serves as the access portal for various data of this Class in the method area.
Verify
The purpose of verification is to ensure that the information contained in the byte stream of the Class file meets the requirements of the current virtual machine and does not endanger the security of the virtual machine itself. It consists of five phases:
1. File Format Verification
Verify that the byte stream conforms to the Class file format and can be processed by the current virtual machine version. For example, ":
A. Do you want to start with magic 0xCAFEBABE?
B. Whether the Primary and Secondary versions are within the processing range of the current Virtual Machine
C. Whether the constants in the constant pool in the Class file are of unsupported constant types.
2. Metadata Verification
Perform Semantic Analysis on the description of bytecode at the class level, for example:
A. Does this class have a parent class?
B. Does this class inherit classes that are not allowed to be inherited, such as final classes?
C. If this class is not an abstract class, does it implement all the methods required to implement the parent class or interface?
D. Whether the fields and methods of the class are in conflict with the parent class
3. bytecode Verification
At the method level, the method body is verified through the analysis of data streams and control flow to ensure that the program semantics is legal and logical. For example, to ensure that the data type of the operands at any time can work with the command code sequence, for example, the data type in the stack is not int but long.
4. symbol reference verification
The verification in this phase occurs when the symbolic reference is converted to a direct reference. This conversion action occurs in the parsing phase to ensure that it can be parsed. Check the following content:
A. can I find the corresponding class using the fully qualified name described by the string in the symbolic reference?
B. Check whether the specified class contains a field descriptor that complies with the method and field described by a simple name.
C. Whether the class, field, and method referenced by the symbol can be accessed by the current class. Shows the permission range:
Preparation
The preparation phase officially allocates memory for the static variable and sets the initial value of the class variable. The memory used by these variables will be allocated in the method area.
| Data Type |
Zero value |
Data Type |
Zero value |
| Int |
0 |
Boolean |
False |
| Long |
0L |
Float |
0.0f |
| Short |
(Short) 0 |
Double |
0.0d |
| Char |
'\ U000000' |
Reference |
Null |
| Byte |
(Byte) 0 |
|
|
Analysis
In the parsing phase, the jvm replaces the symbol reference in the constant pool with the direct reference. Let's take a look at the differences between symbolic reference and direct reference:
Symbol reference: A group of symbols is used to describe the referenced target. A symbol can be a literal in any form. As long as it can be positioned to the target, the target may not be loaded into the memory. The literal form of symbol reference is clearly defined in the standard Class file format of Java virtual machine.
Direct reference: it can be a pointer pointing directly to the target, a relative offset, or a handle that can be simply located to the target. The target must already exist in the memory.
The parsing action mainly applies to class or interface, field, class method, interface method, method type, method handle, and call point qualifier.
Initialization
The initialization stage is the last step in the class loading process. In the previous class loading process, in addition to the user's application can participate in the loading stage through the custom class loader, other actions are completely dominated and controlled by virtual machines. At the initialization stage, java code (or bytecode) defined in the execution class is actually started ).
In this phase, the static statement will be executed first, including the definition of Class variables and the block of the static {} statement, and then the class constructor will be executed. The static statement block can only access the variables defined before the static statement block and those defined after it. The previous static statement block can be assigned a value, but cannot be accessed. For example:
Public class Test {
Static {
I = 0;
// System. out. println (I); // the compiler will prompt "invalid forward reference"
}
Static int I = 1;
Public static void main (String [] args ){
System. out. println (Test. I); // The output is 1.
}
}
Because the parent class always executes initialization first, this means that the parent class static Statement> the static statement of the subclass> the constructor of the parent class> the constructor of the subclass (> indicates that the execution time is earlier than the execution time ).
Public class TestInit extends Parents {
Static {
System. out. println ("A1 ");
}
Public TestInit (){
System. out. println ("A2 ");
}
Public static void main (String [] args ){
New TestInit ();
New TestInit ();
}
}
Class Parents {
Static {
System. out. println ("B1 ");
}
Public Parents (){
System. out. println ("B2 ");
}
}
The execution result of the above Code is B1 A1 B2 A2 B2 A2. In the same class loader, a type is initialized only once.
In addition, you must note that the static statement block cannot be used in the interface. Unlike the class, the parent interface is initialized only when the variables defined in the interface are used.
The following describes the class loaders.
The Class Loader uses Parents Delegation Model: If a Class Loader receives a request for class loading, it will not try to load the class by itself first, instead, it delegates the request to the parent loader to complete the process. This applies to class loaders at every level. Therefore, all loading requests should be finally transmitted to the top-layer startup class loaders, only when the parent class loader reports that it cannot complete the load request will the Child class attempt to load it. As shown in, the first three are system loaders, and the lowest layer can also have their own loaders. The following is the search range of the three loaders (you can also modify the parameter to point to different ranges ):
A. Start the Class Loader: load it in Classes in \ lib
B. Extended Class Loader: Load \ Lib \ ext directory
C. Load the specified class library on the user ClassPath.