JVM core knowledge - class loading mechanism

JVM class life cycle includes seven stages, loading, preparation, validation, parsing, initialization, use and uninstall. In which the preparation, validation, parsing is classified as the connection phase.image.png

load

jvm done in this phase of work

  • Get the name of the class by class binary byte stream
  • This represents the byte stream of static storage structure into a run-time data structure area method
  • Generating a representative of the class in the heap of java.lang.classentry objects, the data in the process as the access class area

At this stage the developer can get control binary byte stream, that is, you can make your own customized operating through custom class loader.

verification

As the name suggests, verify the correctness of the class is loaded.

  • File format validation: validation of a byte stream for compliance with Class file format; for example: whether the beginning 0xCAFEBABE
  • Metadata authentication: described bytecode information semantic analysis, to ensure compliance with the information which describes the Java language specification requires
  • Bytecode verification: the data flow and control flow analysis to determine the semantics of the program is legitimate, logical.
  • Verification of symbolic references: the analysis operation can be performed to ensure correct

ready

Allocate memory for the class static variable, and initializes its default values

  • Only static variable memory allocation
  • Initialization Default value is the default type (i.e., int: 0, boolean: false ...), not the code display setting initial values
  • If it is final staticmodified it will assign an initial value of a variable code (ie: final static int val = 3, 3 is assigned time val, instead of 0)

Resolve

The class reference symbol is converted into a direct reference is a symbolic reference to describe the target set of symbols (e.g.: ArrayList). Direct reference is the direct pointer to the object, an indirect or offset relative to the positioning target handle.

initialization

Initialize the class variables

  • Defined class variables initialized
  • Static initialization code block

Class initialization triggering scenes

  • Create a class instance, that new objects
  • Access static variables
  • Accessing static method
  • Reflection call (i.e. Class.forName ( "com.xxx.Obj"), Obj class is initialized)
  • Subclass are initialized, the parent class is initialized

Class loader

  • Boot class loader (BootStrap ClassLoader): under jrelib be responsible for loading the next parameter specifies the path or -Xbootclasspath jvm identification library. Developers can not directly use
  • Expand the class loader (ClassLoader Extension): , sun.misc.Launcher$ExtClassLoaderwhich is responsible for loading jrelibext directory or specified by java.ext.dirs system variables in the path of all the libraries. Developers can be used directly.
  • Application class loader (the Application ClassLoader): , sun.misc.Launcher$AppClassLoaderwhich is responsible for loading the user class path (the ClassPath) specified class. Developers can directly use
  • Custom class loader (Custom ClassLoader): The user can customize the class loader

Parent delegation model

image.png

Parents delegate implementation of the model, when a class loader needs to load class, this task will be delegated to the parent class loader, turn up drunk to start up top class loader, if the parent can not be loaded, and then load their own processing . Parents benefit delegation model is to ensure that the same type of environment is only one of the same class. That condition is the JVM determines whether a class is the same, whether the same class loader , the same class itself. Code Example:

public class ClassLoaderTest {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        // 使用ClassLoaderTest的类加载器加载本类

        Object obj1 = ClassLoaderTest.class.getClassLoader().loadClass("com.ognice.ClassLoaderTest").newInstance();
        System.out.println(obj1.getClass().getClassLoader());
        System.out.println(obj1 instanceof ClassLoaderTest);

        // 使用自定义类加载器加载本类
        ClassLoader customClassLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                System.out.println("custom classloader loading " + name);
                String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                InputStream stream = getClass().getResourceAsStream(fileName);
                if (stream == null) {
                    return super.loadClass(name);
                }
                try {
                    byte[] b = new byte[stream.available()];
                    stream.read(b);
                    return defineClass(name, b, 0, b.length);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 父级找class
                return super.loadClass(name);
            }
        };
        Object obj2 = customClassLoader.loadClass("com.ognice.ClassLoaderTest").newInstance();
        System.out.println(obj2.getClass().getClassLoader());
        System.out.println(obj2 instanceof ClassLoaderTest);
    }

}复制代码

Results of the

sun.misc.Launcher$AppClassLoader@18b4aac2
true
custom classloader loading com.ognice.ClassLoaderTest
custom classloader loading java.lang.Object
custom classloader loading java.lang.ClassLoader
custom classloader loading com.ognice.ClassLoaderTest$1
com.ognice.ClassLoaderTest$1@277c0f21
false复制代码

This article from the blog article multiple platforms OpenWrite release!

Guess you like

Origin juejin.im/post/5daf0969e51d4524b05a78bb