Loading sequence of ClassLoader

Load >> Verify >> Prepare >> Parse >> Initialize >> Use >> Uninstall

  1. Load: the bytecode file is searched on the hard disk and read through IO. It is loaded only when the Class is used. The main() method of the Class is called, the new object and so on

  2. Validation: Verifies the correctness of the bytecode file

  3. Preparation: Allocates memory to static variables of the class and assigns default values

  4. Resolution: the replacement symbol references for direct reference to the stage will put some static methods (symbol references, such as the main method) replaced with the pointer to the data storage, memory, or handle, etc. (reference) directly, this is the so-called static linking process (complete) during class loading, dynamic linking is done during the program is running will use replacement for direct reference symbols

  5. Initialization: Initialize static variables of a class to specified values. Execute static code blocks. When a class is loaded into a method area, it contains runtime constant pool, type information, field information, method information, reference to the class loader, reference to the corresponding class instance, etc.

Class loader reference: this class-to-class instance reference to a class instance reference: After the classloader puts the loading class information into the method area, it creates an object instance of the corresponding class type and puts it in the heap so that developers can access the details of the class definition in the method area.

Parent delegation mechanism

Java has built-in BootstrapLoader, ExtClassloader, and AppClassLoader. Its loading sequence is shown in the following figure

// jdk1.8 ClassLoader source code
protectedClass<? > loadClass(String name,boolean resolve)
    throws ClassNotFoundException
{
    synchronized (getClassLoadingLock(name)) {
        // Check the AppClassLoader cache to see if it has been loadedClass<? > c = findLoadedClass(name);if (c == null) { / / not found
            long t0 = System.nanoTime();
            try {
                // If parent is not null, recurse to the current method
                if(parent ! =null) {
                    // ExtClassLoader
                    c = parent.loadClass(name, false); 
                } else { // BootstrapClassLoader == ExtClassLoader.parent == nullc = findBootstrapClassOrNull(name); }}catch (ClassNotFoundException e) {
            }
            // If you can't find it, go to AppClassLoader
            if (c == null) {
                longt1 = System.nanoTime(); c = findClass(name); sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); }}if (resolve) {
            resolveClass(c);
        }
        returnc; }}Copy the code