class loading mechanism
The Java Virtual machine loads the data of the description class from the class file into memory, verifies and initializes the data, and finally forms the Java type that can be used directly by the virtual machine, which is the loading mechanism of the virtual machine.
Class starts from being loaded into the virtual machine's memory, and its entire lifecycle includes: Load (Loading), validate (verification), prepare (preparation), Parse (Resolution), Initialization (initialization), use (using), and unload (unloading) seven phases. Where the validation, preparation, and parsing of three parts is collectively referred to as the connection (linking), the sequence of the seven phases is as follows:
As shown, the order of the five stages of loading, validating, preparing, initializing, and unloading is determined, and the loading process of the class must begin in this order, and the parsing phase is not necessarily, and in some cases it can start again after the initialization phase.
Each phase of a class's life cycle is usually cross-mixed, often invoking or activating another phase during one phase of execution.
first, the time of class loading
Active referencing: A class that is actively referenced will trigger the initialization process (load, verify, prepare to start before this is needed)
1) When encountering the 4 bytecode directives of new, getstatic, putstatic, or invokestatic, 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.
2) When using the Java.lang.reflect package method to make a reflection call to a class, if the class has not been initialized, it needs to trigger its initialization first.
3) When starting a class, it is necessary to trigger the initialization of the parent class if it is found that the parent class has not yet been initialized.
4) 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 class first.
5) When using jdk7+ 's dynamic language support, if the final parse result of the Java.lang.invoke.MethodHandle instance is ref_getstatic, Ref_putstatic, ref_invokestatic method handle, And the class that corresponds to this method handle is not initialized, the trigger is initialized first. (More Java dynamic type language materials: http://www.infoq.com/cn/articles/jdk-dynamically-typed-language)
Passive References: A class that does not trigger the initialization process if it is a passive reference
1) referencing a static field of a parent class through a subclass does not cause subclasses to initialize. For a static field, only the class that directly defines the field is initialized, so when we refer to a static field defined in the parent class through a subclass, only the initialization of the parent class is triggered, not the initialization of the subclass.
2) referencing a class through an array definition does not trigger initialization of this class.
3) Constants are stored in the constant pool of the calling class at compile time and are not inherently referenced directly to classes that define constants, so initialization of classes that define constants is not triggered.
second, class loading process
1. Loading
During the load phase, the virtual machine needs to complete the following three things:
1. Obtain a binary byte stream that defines this class by naming the permissions of a class.
2. Convert the static storage structure represented by this byte stream into the run-time data structure of the method area.
3. Generate a Java.lang.Class object representing this class in the Java heap as the access entry for the data in the method area.
Relative to the other stages of the class loading process, the load phase is relatively strong during the development phase, which can be done either with the system-provided ClassLoader or by a user-defined ClassLoader, which the developer can use to define its own classloader to control how the byte stream is fetched.
2. Verification
The purpose of the validation is to ensure that the byte stream in the class file contains information that conforms to the requirements of the current virtual machine and does not compromise the security of the virtual machine itself. Implementations of different virtual machines for class validation may vary, but the following four phases of validation are generally performed: file format validation, metadata validation, bytecode validation, and symbolic reference validation.
1)Validation of file formats: Verifies that the byte stream conforms to the specification of the class file format and can be processed by the current version of the virtual machine, the primary purpose of which is to ensure that the input byte stream is correctly parsed and stored
Within the method area. After this phase of validation, the byte stream is stored in the memory's method area, and the subsequent three validations are based on the storage structure of the method area.
2)meta-data validation: The semantic validation of the metadata information of a class (in fact, the syntax check of each data type in the Class) ensures that there is no metadata information that does not conform to the Java syntax specification.
3)byte code verification: The main work of this phase is to perform data flow and control flow analysis, and verify the method body of the class to ensure that the method of the checked class does not make the behavior that endangers the virtual machine security at runtime.
4)Symbol Reference Validation: This is the final phase of validation, which occurs when a virtual machine converts a symbolic reference to a direct reference (the conversion occurs during the parsing phase, which is explained later), and is primarily a matching check for information other than the class itself (a variety of symbol references in a constant pool).
3. Preparation
The prep phase is a phase that formally allocates memory for class variables and sets the initial value of class variables, which are allocated in the method area.
Note:
1) The memory allocation at this time includes only class variables (static), not instance variables, and instance variables are allocated to the Java heap as the object is instantiated when the object is initialized.
2) The initial value set here is typically the default 0 value of the data type (such as 0, 0L, NULL, FALSE, and so on), rather than being explicitly assigned to the value in Java code.
4. Analysis
The parsing phase is the process by which a virtual machine replaces a symbolic reference within a constant pool with a direct reference.
Symbol Reference(Symbolic Reference): A symbol reference describes a target in a set of symbols, a symbol reference can be any form of literal, the symbolic reference is independent of the memory layout implemented by the virtual machine, and the target of the reference is not necessarily in memory.
Direct ReferenceDirect reference can be a pointer to a target directly, a relative offset, or a handle that can be Reference to a target indirectly. The direct reference is related to the memory layout implemented by the virtual machine, and the direct reference that the same symbol reference is translated on different virtual machine instances is generally not the same, and if there is a direct reference, the referenced target must already exist in memory.
1. Parsing of classes or interfaces: Determine whether the direct reference you want to convert is an array type or a reference to an ordinary object type for different parsing.
2. Field parsing: When parsing a field, first find in this class whether it contains a field with a simple name and a field descriptor that matches the target, and if so, the end of the search, and if not, the individual interfaces and their parent interfaces implemented by the class are searched recursively according to the inheritance, not yet, The parent class is searched recursively from top to bottom according to the inheritance relationship until the lookup is finished.
3, class method analysis: The parsing of the class method is similar to the search step for the field resolution, but it is more to determine whether the method is in the class or interface, and the matching search for the class method is to search the parent class and then search the interface.
4, interface method analysis: Similar to the class method resolution step, except that the interface does not have a parent class, so it is only a recursive search for the parent interface.
5. Initialize
The class initialization phase is the last step in the class loading process, in addition to the load (Loading) stage in which the user application can participate through a custom ClassLoader, the rest of the action is entirely dominated and controlled by the virtual machine. In the initialization phase, the Java program code defined in the class is actually started.
The initialization phase is the process of executing the class constructor <clinit> () method.
1) The <clinit> () method is generated by the combination of the assignment action of all class variables in the compiler's auto-collection class and the statements in the static statement block (static{} block), the order in which the compiler collects is determined by the order in which the statements appear in the source file.
2) The <clinit> () method differs from the constructor of a class in that it does not need to explicitly call the parent class constructor, which guarantees that the <clinit> () method of the parent class has been completed before the subclass's <clinit> () method executes. So the first class of the <clinit> () method that executes in the virtual machine must be java.lang.Object.
3) because the parent class's <clinit> () method executes first, it means that the static statement block defined in the parent class takes precedence over the subclass's variable assignment operation.
4) The <clinit> () method is not required for a class or interface, and the compiler can not generate an <clinit> () method for this class if there is no static statement block in the class and no assignment to the variable.
5) There may be variable assignment operations in the interface, so the interface also generates the <clinit> () method. However, unlike classes, 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 variable defined in the parent interface is used. In addition, the implementation class of the interface does not execute the <clinit> () method of the interface at initialization time.
6) Virtual opportunity ensures that the <clinit> () method of a class is properly locked and synchronized in a multithreaded environment. If there are multiple threads to initialize a class at the same time, there will only be one thread executing the class's <clinit> () method, and the other threads will need to block the wait until the active thread executes the <clinit> () method. If there is a lengthy operation in the <clinit> () method of a class, it can cause multiple processes to block.
three, parental assignment model
Three types of class loaders that are pre-defined by the JVM:
1) Start (Bootstrap) ClassLoader: is a class loader implemented with native code that is responsible for loading the class library below <java_runtime_home>/lib into memory (such as Rt.jar). Because the boot ClassLoader involves the virtual machine local implementation details, the developer cannot directly get a reference to the startup ClassLoader, so it is not allowed to operate directly from the reference.
2) Standard extension (Extension) class loader: is implemented by Sun's Extclassloader (Sun.misc.launcher$extclassloader). It is responsible for loading the < Java_runtime_home >/lib/ext or the class library in the specified location java.ext.dir the system variable into memory. Developers can use the standard extension class loader directly.
3) System Class Loader: is implemented by Sun's Appclassloader (Sun.misc.launcher$appclassloader). It is responsible for loading the class library specified in the System class path (CLASSPATH) into memory. Developers can use the System class loader directly.
Parent delegation Mechanism Description:
When a particular class loader receives a request to load a class, it first delegates the load task to the parent class loader, recursively, and returns if the parent ClassLoader can complete the class load task, only to load itself when the parent ClassLoader cannot complete the load task.
Java class loading mechanism detailed