Note : The Class file described in this article is not specifically a file that exists in a specific disk, but a string of binary byte streams, regardless of the form in which it exists.
1. Introduction
A Java class is compiled by a virtual machine into a class bytecode file that contains various descriptive information that ultimately needs to be loaded into the virtual machine before it can be run and used. So how does a virtual machine load these Class files? What happens after the information in the Class file enters the virtual machine? Next we'll discuss it one by one.
2. Timing of class loading
The entire life cycle of a class consists of seven stages of loading, validating, preparing, parsing, initializing, using, and unloading, in which the validation, preparation, and parsing of 3 parts are collectively referred to as connections.
In, the order of the 5 phases of loading, validating, preparing, initializing, and unloading is determined, and the loading process of the class must begin with a step-by-step process, in which the loading process of another class can be inserted. So, under what circumstances do you need to start the first stage of the class loading process? The virtual machine specification strictly stipulates that there are only 5 cases in which the class must be "initialized" immediately.
- When you encounter the 4 bytecode directives of new, getstatic, putstatic, or invokestatic, if the class is not initialized, you need to trigger its initialization first. The most common Java code scenario for generating these 4 instructions is when instantiating an object using the New keyword, reading or setting a static field of a class (except for the static fields that are final, which have been placed in a constant pool by the compiler), and when invoking a static method of a class.
- When you use the Java.lang.reflec package method to make a reflection call to a class, if the class has not been initialized, you need to trigger its initialization first.
- When initializing a class, if it is found that the parent class is not initialized, the initialization of its parent class needs to be triggered first
- When the virtual machine starts, the user needs to specify a class to execute (the class that contains the main method), and the virtual opportunity initializes the main class first
- When using dynamic language support for JDK1.7, if a Java.lang.invoke.MethodHandle instance parses the result ref_getstatic, Ref_pubstatic, ref_invokestatic method handle, And the class that corresponds to this method handle is not initialized, you need to initialize the class first. (It doesn't understand what it is)
3. Class loading process
Knowing when the class is starting to load, let's take a look at the whole process of class loading. That is, loading, validating, preparing, parsing, and initializing this 5-phase concrete action.
3.1 Loading
Note : "Load" is a phase of the "class loading" process, where the virtual machine needs to complete the following 3 things during the load phase:
- A binary byte stream that defines this class is obtained through the fully qualified name of a class, where the fully qualified name of the class can be obtained from a path, such as a ZIP packet, a network, a dynamic proxy, and so on.
- Convert the static storage structure represented by this byte stream into the runtime data structure of the method area
-
A Java.lang.Class object representing this class is generated in memory as a access entry for various data of this class in the method area.
3.2 Verification
During the load phase, the class file does not have to be compiled with Java source code and can be generated in any way, even with a hex editor that is written directly to produce a class file. Therefore, in order to ensure the security of the virtual machine, the verification phase is very necessary, the workload of the verification phase accounted for a large part of the virtual machine's class loading subsystem. It will generally complete the following 4 stages of the inspection action.
- File Format Verification
- Metadata validation, that is, whether the file description information conforms to the Java syntax rules, primarily verifies that the class's data type is correct, such as whether the class has a parent class, whether the class's parent inherits classes that are not allowed to inherit, and so on.
- Bytecode verification, this verification process is mainly for the method body of the class, to ensure that the class method being tested will not do harm to the virtual machine.
-
Symbol reference validation, which determines whether the class information referenced in the class can be accessed or has access (more private, protected modifier access).
3.3 Preparation
The prep phase is a phase that formally allocates memory for class variables and sets class variable initialization, and the memory used by these variables is allocated in the method area.
There are two points to note here, first of all, the variables initialized at this stage are class variables, which are static modified variables, excluding instance variables. Instance variables are assigned to the Java heap along with the object when the object is initialized. Second, the initialization in this case is a 0 value of the data type, such as a variable public static int value = 123 , its first initialized to 0, and the class becomes 123 after the first initialization.
It says it's usually the case, and there are, of course, some "unusual situations", such as public static final int value = 123 . The final modified variable produces the corresponding value at this stage.
3.4 Parsing
The parsing phase is the process by which a virtual machine replaces a symbolic reference within a constant pool with a direct reference. Its complete task is to validate the symbol reference in the validation phase. Mainly by the following 4 kinds of parsing process
- Class or interface parsing
- Field resolution
- class method parsing
-
Interface Method Parsing
3.5 initialization
In the preparation phase, the primary is to assign values to class variables (the general type is assigned to 0,boolean to false, and so on), while the initialization phase is the process of initializing class variables and other resources, which is the execution of the class constructor <clinit> () method. Here are some features and details that may affect the behavior of your program:
- The <clinit> () method collects assignment actions for class variables and statements that execute static statement blocks. Static statement blocks can only assign values to variables that are defined behind a statement block, but cannot access variables defined behind a statement block. For example
public class Test{ static{ i = 0; // 给变量赋值可以正常编译通过 System.out.println(i); // 这句编译器会提示「非法向前引用」 } static int i = 1;}
- The <clinit> () method differs from the constructor of a class in that it does not require a display to call the parent class constructor, and the virtual machine guarantees that the parent class's <clinit> () has been executed until the subclass's <clinit> () method executes. Therefore, the first class that is executed in the virtual machine <clinit> () method must be
java.lang.Object .
- Because the <clinit> () method of the parent class executes first, the static statement block defined by the parent class is preceded by the static statement block of the child class.
- Virtual opportunities Ensure that a <clinit> () method of a class is correctly locking and synchronized in a multithreaded environment, and that if multiple threads initialize a class at the same time, just this class of the <clinit> () method takes a long time, which can cause multiple processes to block. For example
static class DeadLoadClass{ static{ if(true){ System.out.println(Thread.currentThread()+"init DeadLoopClass"); while(true){} } }}public static void main(String[] args){ Runnable srcipt = new Runnable(){ public void run(){ System.out.println(Thread.currentThread()+"start"); DeadLoadClass dlc = DeadLoadClass(); System.out.println(Thread.currentThread()+"run over"); } }; Thread t1 = new Thead(script); Thread t2 = new Thead(script); t1.start(); t2.start();}
The results are as follows: One thread has been operating for a long time in a dead loop, another thread has been blocked, and has been waiting.
Thread[Thread-0,5,main]startThread[Thread-1,5,main]startThread[Thread-0,5,main]init DeadLoopClass
4. Class Loader
The virtual machine design team takes the "fully qualified name of a class to obtain a binary byte stream that describes this class" in the class loading phase, which is implemented outside the Java virtual machine, so that the application can decide for itself how to get the required class. The code module that implements this action is called the class loader.
Class 4.1 and Class loader
The role of the ClassLoader in Java programs is far from being limited to the load phase of classes. In the run phase, compare whether two classes are "equal", only if the two classes originate from a class file, are loaded by the same virtual machine, and the same class loader is loaded, the two classes are equal.
The "equality" referred to here includes the return results of the methods, equals methods, and methods that represent class objects, isAssignableFrom isInstance as well as the use of keywords to determine the relationship of the object to which they instanceof belong.
4.2 Parental delegation Model
Most Java programs use the following 3 types of system-provided ClassLoader
- Start the ClassLoader: This classloader is responsible for loading the class libraries stored in the <java_home>\lib directory into the virtual machine memory.
- Extension ClassLoader: Implemented by this loader
sun.misc.Launcher$ExtClassLoader , it is responsible for loading the <java_home>\lib\ext directory, or all class libraries specified by the JAVA.EXT.DIRS system variable.
- Application ClassLoader: Implemented by this class library loader
sun.misc.Launcher$AppClassLoader , it is responsible for loading the class library specified on the user path (ClassPath). If the application does not have a custom classloader, this is the default class loader in general.
Our applications are loaded with each other by these 3 kinds of loaders, and you can customize the ClassLoader if necessary. The relationships between these classloader are as shown, and this hierarchical relationship is known as the class loader's parental delegation model.
The working process of the parent delegation model is that if a class loader receives a class load requirement, it does not attempt to load the class first, but instead delegates the request to the parent ClassLoader to complete, so that all the load requests should eventually be routed to the top-level startup class loader. The child loader tries to load itself only when the parent loader has feedback that it cannot load the request (it does not find the desired class in its search scope).
One obvious benefit of the parental delegation model is that the Java class has a hierarchical relationship with precedence as its classloader. When an java.lang.Object object is customized, there is code in the object that endangers the program, but it is not loaded because the object class is loaded by the startup ClassLoader, which in some way guarantees the security of the program.
The above is a summary of the virtual machine class loading mechanism, mainly from the "in-depth understanding of Java Virtual Machine" book.
Loading mechanisms such as Java virtual machines