The class loading process has the following steps

  • Load >> Verify >> Prepare >> Parse >> Initialize >> Use >> Uninstall
  1. Load: a bytecode file is searched on the hard disk and read through IO. It is loaded only when the Class is used, such as calling the main() method of the Class, the new object, etc. During the load phase, a java.lang.Class object representing the Class is generated in memory, which acts as an access point to the various data of the Class in the method area
  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) to replace for the pointer to the data storage, memory, or a 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: Executes a static block of code to initialize a class’s static variable to the specified value

Class loader initialization process

Create a JVM Launcher instance sun.misc.Launcher. The sun.misc.Launcher initialization uses a singleton design that ensures that there is only one instance of Sun.misc.Launcher in a JVM. Within the Launcher construction method, it creates two class loaders, respectively is sun misc. The Launcher. ExtClassLoader (extension class loader) and sun. Misc. The Launcher. AppClassLoader (application class loader). By default, the JVM loads our application using an instance of the AppClassLoader returned by the getClassLoader() method of the Launcher.

In fact, there is a parent delegation mechanism for class loading. When a class is loaded, it first entrusts the parent loader to find the target class, and then entrusts the upper parent loader to load it. If all the parent loaders cannot find the target class in their own class loading path, they will find and load the target class in their own class loading path. The parent delegate mechanism is simply that the father loads it first, and if not, the son loads it

Why design parental delegation?

  • Sandbox security: Self-written java.lang.String.class classes are not loaded, which prevents the core API library from being tampered with
  • Avoid class reloading: When the parent has already loaded the class, there is no need for the child ClassLoader to load it again to ensure the uniqueness of the loaded class

Take full responsibility for the delegation mechanism

“Full responsibility” means that when a ClassLoder loads a class, unless another ClassLoder is displayed, the classes that the class depends on and references are also loaded by that ClassLoder