"In-depth understanding of the Java virtual machine" learning - class loading mechanism

"In-depth understanding of the Java virtual machine" learning - class loading mechanism

1 Overview

The virtual machine data that describes the classes loaded from Class file into memory, and verify the data, and converts parsing initialization, forming Java type can be used as a virtual machine, which is a virtual machine class loading mechanism.


2. class loading time

2.1 class life cycle:

Load -> connection (verify -> Preparation -> Analytical) -> Initialization -> use -> Uninstall

Among them, loading, validation, preparation, initialization and unloading sequence of five stages is determined, class loading process must begin step by step in this order, and not necessarily analytical phase: in some cases it can be initialized after the restart phase, which is to support the Java language run-time binding.

2.2 initialization class

And only four cases of the class must be "initialized" immediately:

  • Encounter new, getstatic, or putstatic invokestatic when this four-byte code instructions, if the class is not been initialized, initialization is required to trigger their

    Scenes:

    1. Use the new keyword to instantiate an object
    2. Read or set a static field of a class (the final modification, the compiler has been the result into the constant pool except for static fields)
    3. Call a static method of class time
  • Use java.lang.reflectwhen the package approach to reflect the class to call, if the class is not been initialized, you need to trigger their initialization

  • When initializing a class, if you find the parent class has not been initialized, you need to trigger initialization of the parent class

  • When the virtual machine starts, the user needs to specify the main class (to be performed include a main()method of that class), the virtual machine to initialize this master class


3. class loading process

3.1 Load

In the loading phase, the virtual machine needs to do three things:

  • To obtain such a binary byte stream defined by the fully qualified name of a class
  • This represents the byte stream of static storage structure into a run-time data structure area method
  • Generating a Java heap representatives of this class of java.lang.Classthe object, as a method for accessing the data entry area

3.2 verification

We will complete the verification process of four stages:

  1. File format validation
  2. Metadata validation
  3. Bytecode verification
  4. Verification of symbolic references

3.3 Preparation

Preparation phase is formally allocate memory for class variables and set the stage class variable initial values, this memory will be in the method area allocated in.

Note several points:

  • This time includes only the memory allocation class variables (static variables to be modified) , and does not include the instance variables, instance variables will be assigned along with the object when the object is instantiated Java heap in (initialization phase).

  • Here the initial value "normally" is the data type of zero value (e.g., 0,0L, null, false, etc.), rather than the values are given explicitly in Java code.

    for example:

    // 变量 value 在准备阶段过后的初始值为 0 而不是 123
    public static int value = 123;
  • Special case: if there is attribute table ConstantValue class attribute field in the field (i.e., constant final), and that in the preparation stage variable value is initialized to the value specified by the property ConstantValue.

    for example:

    // 编译时 Javac 将会为 value 生成 ConstantValue 属性,在准备阶段虚拟机就会根据 ConstantValue 的设置将 value 赋值为 123
    public static final int value = 123;

3.4 parsed

Parsing stage is a virtual machine to a constant pool of symbolic references to the process of replacing direct references.

Concept Note:

  • Reference symbol: a symbol reference target set of symbols to be described in the referenced, literal symbols may be in any form, can be positioned unambiguously as long as the goal to use. Symbol reference has nothing to do with the memory layout to achieve a virtual machine, the goal is not necessarily a reference has been loaded into memory.
  • Direct references: a direct reference may be direct pointer to the object, a relative offset or indirectly targeted to handle targets. Direct reference is to achieve the memory layout associated with the virtual machine, quote translated on a virtual machine instance with a different symbol is generally not directly referenced the same. If you have a direct reference to that target reference must already exist in memory.

3.5 Initialization

Class initialization phase is the last step of the process of class loading foregoing class load ( preparation phase ), except during the load phase the user application can define the class loader from the outside of participation, the remaining operation is completely dominated by the virtual machine and control. To the initialization phase, really started classes defined in Java code.

Initialization phase is performed class constructor <clinit>()procedure of Method :

During the preparation phase, class variables have been assigned an initial value once the system requirements, and in the initialization phase, it is to initialize class variables and other resources (such as class member variables based on subjective programmers plan developed by the program - in addition to variables outside of class the variables are class member variables).

Several concepts to keep in mind:

  1. <clinit>()The method of operation is the assignment statement block and a static compiler automatically collect all classes class variables ( static{}block) merge statements generated ( there is a preference {} static )

  2. Virtual opportunity to ensure that the subclass <clinit>()before execution method, the parent class's <clinit>()method has already been implemented. Therefore, the first virtual machine to be executed <clinit>()class method certainly java.lang.Object.

  3. As the parent class <clinit>()method to perform first, which means a static block of statements as defined in the parent class takes precedence over variable subclass assignment.

    For example, the following code values ​​operation result field B would be 2 instead of 1.

    static class Parent {
        public static int A = 1;
        static {
            A = 2;
        }
    }
    static class Sub extends Parent {
        public static int B = A;
    }
    public static void main(String[] args) {
        System.out.println(Sub.B);
    }
  4. <clinit>()A method for a class or interface is not necessary, if a class is not a static block of statements, there is no assignment of the variable, then the compiler can not generate the class <clinit>()method.

  5. Interface block static statements can not be used, but there is still initialized variable assignment, and therefore generates the same class interface <clinit>()methods.


4. The class loader

4.1. Comparison of the two classes whether "equal"

Only in these two categories is loaded under the premise of the same class loader makes sense, otherwise, even if these two classes is a Class from the same file, as long as they are of a different class loader, and that these two classes it is certainly not equal.

4.2 class loader

Different class loader (Java virtual machine angle)
  1. Start class loader (C ++ implementation): part of the virtual machine itself
  2. All other class loaders (Java implementation): independent of external virtual machine, inherited from abstract class java.lang.ClassLoader
Different class loader (Java developer's perspective)
  1. Boot class loader: consistent with the above

    Responsible will be stored in <JAVA_HOME>\libthe directory, or the -Xbootclasspathparameter designated path, and a virtual machine identification library is loaded into the virtual machine memory. Start class loader can not be directly referenced Java programs.

  2. Extension class loader: the sun.misc.Launcher$ExtClassLoaderrealization

    Responsible for loading <JAVA_HOME>\lin\extthe directory, or by java.ext.dirsall the libraries, the developer system variables specified path can be used directly extended class loader

  3. Application class loader: the sun.misc.Launcher$AppClassLoaderimplementations

    Since the class loader is ClassLoaderthe getSystemClassLoader()return value of the method, it is generally called the system class loader. It is responsible for loading the user path (ClassPath) designated libraries, developers can directly use this class loader, if the program should not have been their custom class loader, in general, this is the program in the default class loader device.


4.3 parent delegation model (important)

Above:

structure:

In addition to the parent delegation model requires top-level boot loader class, the rest of the class loader should have its own parent class loader. Here parent-child relationship between the class loader is generally not achieved to inheritance relationship, but use a combination of the code multiplexing relationship with the parent loader.

work process:

If a class loader loads the class received a request, it will not be his first attempt to load the first class, but to delegate this request to the parent class loader to complete each level of the class loader is true, so all the final loading request should be sent to the top of the boot class loader, only when the parent class loader to load the feedback they can not complete the request (in its search did not find the desired category), sub-loader will try themselves to load.

The principle
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    // 首先,检查请求的类是否已经被加载过了
    Class c = findLoadedClass(name);
    if (c == null) {
        try {
            if (parent != null) {
                c = parent.loadClass(name, false);
            } else {
                c = findBootstrapClassOrNUll(name);
            }
        } catch (ClassNotFoundException e) {
            // 如果父类加载器抛出 ClassNotFoundException
            // 则说明父类加载器无法完成加载请求
        }
        if (c == null) {
            // 在父类加载器无法加载的时候
            // 再调用本身的 findClass 方法进行类加载
            c = findClass(name);
        }
    }
    if (resolve) {
        resolveClass(c);
    }
    return c;
}

First check had already been loaded, call the parent if the loader does not load loadClass()method, if the parent loader to empty the default boot loader as the parent class loader. If the parent fails to load, then throws ClassNotFoundExceptionafter an exception, then call their own findClass()methods for loading.

Java does not meet the delegation model example of parents
  1. Base class needs to call back to the user code

    • Reference to the context class loader (Thread Context ClassLoader), by the class loader java.lang.Threadclass setContextClassLoaser()method of setting has not been set if the thread is created, it will inherit from a parent thread; if both globally application was not set, then the default class loader is the application class loader.

    • Because the parent class loader class loader request to complete the sub-class loading operation, the reverse is actually using a class loader, parents do not meet the delegation model.

    • Such as: JDBC

  2. Dynamic program

    • The hot code Alternatively, thermal module deployment. (In fact, modular operating)

    • This modular standard model we call "OSGi". (Class loader mechanism implement custom)

    • In this standard, each program module (Bundle) has its own class loader, needs to be replaced when a Bundle, Bundle put together replaced even grade heat loading to effect the replacement code.
    • In the OSGi environment, the tree is no longer a class loader delegation model is the result of both parents, but the further development of the network structure.

Guess you like

Origin www.cnblogs.com/weixuqin/p/11412553.html