Reprint---Virtual machine class loading mechanism

Source: Internet
Author: User

virtual machine class loading mechanism

The virtual machine loads the data of the described class from the class file into memory, verifies the data, transforms parsing and initializing, and finally forms the Java type that can be used directly by the virtual machine, which is the class loading mechanism of the virtual machine.

time of class loading

Class is loaded into the virtual machine memory to begin with, until the memory is unloaded. Its entire lifecycle includes: class loading (Loading), validation (verification), preparation (preparation), parsing (Resolution), initialization (initialization), Use (using) and unload (unloading) 7 stages. Where validation, preparation, parsing 3 parts collectively referred to as the connection (linking).

The virtual machine specification strictly specifies that there are only 5 cases in which the class must be "initialized" immediately:

  1. When you encounter the 4 bytecode directives of new, getstatic, putstatic, or involvestatic, if the class has not been initialized, you need to trigger its initialization first.
  2. 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.
  3. 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.
  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 JDK1.7 's dynamic language support, if the Java.lang.invoke.MethodHeadle instance, the final parse result ref_getstatic, Ref_putstatic, ref_invokestatic method handle, And the class that corresponds to the method handle is not initialized, it needs to be initialized first.
the process of class loading

First, load

(1) During the loading phase, the virtual machine needs to complete the following 3 things:

    1. Gets a binary byte stream that defines this class by using the fully qualified name of a class
    2. Transform 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 memory, as a access entry for various data of this class in the method area

(2) The array class itself is not created by the ClassLoader, which is created directly by the Java Virtual machine.

An array class creation process follows these rules:

    1. If the array's component type (Component type, which refers to an array that is stripped of a dimension's type) is a reference type, recursively uses the loading procedure described above to load the component type, and the array will be identified on the class name space of the class loader that loads the array component type.
    2. If the array's component type is not a 7 reference type, the Java Virtual machine will mark the array as associated with the bootstrap ClassLoader.
    3. The visibility of an array class is consistent with the visibility of its component type, and if the component type is not a reference type, the visibility of the array class is required to default to public

Second, verification

Validation is the first step in the connection phase, which is designed to ensure that the byte stream of a class file contains information that conforms to the requirements of the current virtual machine and does not compromise the security of the virtual machine's province.

The verification phase will roughly complete the following 4-phase verification actions: File format validation, metadata validation, bytecode validation, symbol reference validation

(1) file format verification

    1. The first phase 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.
    2. When the oil passes through this phase of validation, the byte stream is stored in the memory's method area, so the next 3 verification phases are all based on the storage structure of the method area and do not directly manipulate the bytecode.

(2) meta-data validation

    1. The second stage is the semantic analysis of the information described in bytecode to ensure that the information described is in accordance with the requirements of the Java language specification.
    2. The main purpose of the second phase is to make semantic analysis of the metadata information of the class, and ensure that there is no metadata information that does not conform to the Java language specification.

(3) Byte code verification

    1. The third stage is the most complex stage in the whole verification process, the main purpose is to determine the program semantics is legal and logical through data flow and control flow analysis. This phase verifies the method body of the class. Ensuring that the method of the class being validated does not make the time to compromise the virtual machine safe.
    2. For example: Ensure that the data type of the operand stack at any time and the sequence of instruction code can work together. Guaranteed to jump to a bytecode directive other than the method body.

(4) Symbol reference verification

    1. The validation of the last verification phase occurs when a virtual machine converts a symbolic reference to a direct reference, which occurs during the third phase of the connection phase-the parsing phase. Symbolic reference validation can be seen as a matching check of information other than the class itself.
    2. For example, if a fully qualified name in a string description in a symbol reference can find the corresponding class. Whether there is a field descriptor that conforms to the method in a particular class, and the methods and fields described by the simple name
    3. The purpose of the symbol reference validation is to determine that the parsing action will execute properly, and if it cannot be verified by a symbolic reference, the subclass of the Java.lang.IncompatibleClassChangeError exception is thrown

  

Third, 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.

Iv. Analysis

(1) The parsing phase is the process by which a virtual machine replaces a symbolic reference within a constant pool with a direct reference.

    1. Symbol reference (Symbolic Reference): the symbol refers to a set of symbols to describe the target referenced, the symbol can be any form of literal, as long as the use can be ambiguous to locate the reference target. The symbolic reference is independent of the memory layout implemented by the virtual machine, and the referenced target is not necessarily loaded into memory. The memory layouts implemented by various virtual machines can vary, but the symbolic references they can accept must be consistent, since the literal form of the symbol reference is clearly defined in the class file format in the Java Virtual Machine specification.
    2. Direct Reference: A direct reference can be a pointer to a target directly. Relative offset or a handle that can be positioned indirectly to the target. The direct reference is related to the memory layout implemented by the virtual machine, and the direct reference to the same symbol reference on the different virtual machine instances will not generally be the same, if there is a direct reference to the referenced target must already exist in memory.

(2) The virtual machine specification does not specify the time at which the parsing phase occurs, only the execution anewarray,checkcast,getfield,getstatic,instanceof,invokedynamic,invokeinterface is required , Invokespecial,invokestatic,invokevirtual,ldc,ldc_w,multianewarray,new,putfield and putstatic these 16 byte-code directives used to manipulate symbol references, Parsing is preceded by the symbol references that they use.

(3) Parsing actions are mainly for classes or interfaces, fields, class methods, interface methods, method types, method handles, and call Point qualifier 7 class symbol references.

(4) Parsing of classes or interfaces

The complete parsing process for a virtual machine requires the following 3 steps

1) If C is not an array type, the virtual machine will pass the fully qualified name representing N to the class loader of D to load the Class C. During the loading process, because of metadata validation, bytecode verification is required, and other related classes can trigger the load action.

2) If C is an array type and the element type of the array is an object, then the array type will be loaded according to the above rule. If the descriptor of N is as assumed in the previous form, the type of the element needs to be loaded, and then the virtual machine generates an array object representing this array dimension and element.

3) If the above step does not have any exception, then C in the virtual machine is actually a valid class or interface, but after the completion of the parsing is also a symbolic reference validation, confirm that D is the access to C.

(5) Field parsing

(6) Class method parsing

(7) Interface method analysis

V. Initialization

  1. The class initialization phase is the last step in the class loading process
  2. In the preparation phase, the variable has been assigned the initial value of the system, and during the initialization phase, the variables and other resources are initialized according to the programmer's subjective initialization, or can be expressed from a different angle: The initialization phase is the process of executing the class constructor <cninit> () method.
  3. The <clinit> () method is generated by the combination of the assignment of all class variables in the compiler's automatic collection of classes and the statements in the static statement block (static{} block), and the order that the compiler collects 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.
  4. 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 executed before the subclass's <clinit> () method executes. Therefore the class of the first executed <clinit> () method in the virtual machine must have java.lang.object.
  5. The <clinit> () method of the parent class executes first, which means that the static statement block defined in the parent class takes precedence over the child class's variable assignment operation.
  6. The <clinit> () method is not necessary 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 generate the <clinit> () method for this class
  7. The virtual opportunity guarantees that the <clinit> () method of a class is properly locked and synchronized in multiple threading environments.

  

class Loader

First, class and class loader

For any class, it is necessary for the loader to load it and the class itself to establish its uniqueness in the Java Virtual machine, each of which has a separate class namespace.

Two, parental assignment model

(1) From the point of view of the Java virtual machine, there are only two different classloader: one is to start the ClassLoader (Bootstrap class ClassLoader), which uses the C + + language implementation to be a part of the Java Virtual machine automation The other is all other ClassLoader, which are implemented by the Java language, independent of the virtual machine, and all inherit from the abstract class Java.lang.classLoader.

(2) Subdivision: Start class loader (Bootstrap ClassLoader)

Extension class loader (Extension classloadert)

Application class loader (application ClassLoader) [System class loader]

(3) Parental assignment model working process:

If a classloader receives a request from the ClassLoader, it does not attempt to load the class itself, but instead delegates the request to the parent ClassLoader, which is the case for each level of the ClassLoader. Therefore, all load requests should eventually be routed to the top-level ClassLoader only if the parent ClassLoader feedback itself is unable to complete the class load request, the subclass loader will attempt to load itself.

Reprint---Virtual machine class loading mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.