Once the Java compiler has compiled the. Class file, we need to run it using the JVM. The initial task is to input the bytecode from disk into memory, a process we call loading. After loading, we can do a series of pre-run preparations, such as: create space for class static variables, store constant pool in method area memory and implement constant pool address resolution, initialize class static variables, and so on. How does a JVM load a class file?

Class loading mechanism

The life cycle of a class from being loaded into virtual machine memory to being unloaded from memory includes: Load -> Connect (validate -> Prepare -> parse)-> initialize -> Use -> unload


  • loading
    • The class loader is required to load the class file bytecode content into memory, convert the static data into runtime data structures in the method area, and generate a java.lang. class object representing the class in the heap as an access point to the method area class data.
  • link The process of merging the binaries of Java classes into the JVM’s running state
    • Validation: To ensure that the loaded class information complies with the JVM specification and that there are no security issues
    • Preparation: The formal allocation of memory for class variables (static variables) and the setting of their initial values, which will be allocated in the method
    • Resolution: symbolic references to the virtual machine constant pool are replaced by byte-reference procedures
  • Initialize the
    • The initialization phase is the process of executing the class constructor

      () method. The class constructor < Clinit > () method is generated by combining the assignment actions of all class variables in a class with statements in a static block
    • When initializing a class, if the parent class has not been initialized, the initialization of the parent class must be triggered first
    • The virtual machine ensures that a class’s

      () methods are locked and synchronized correctly in a multithreaded environment
    • When scoping a static field of a Java class, only classes that truly name the field are initialized
Java loading classes use the “all-responsible delegation mechanism” :
When a ClassLoader loads a class, unless another ClassLoader is displayed, the classes that the class depends on and references are also loaded by that ClassLoader. “Delegate mechanism” refers to delegating the parent class loader to find the target class, and only looking up and loading it from its own path if it cannot find it. This is for security reasons. Imagine if someone wrote a malicious base class (such as java.lang.String) and loaded it into the JVM.