Detailed explanation of the loading mechanism and life cycle of the class

Class loading mechanism

The Java virtual machine loads the data describing the class from the Class file into the memory, verifies, converts, analyzes, and initializes the data, and finally forms a Java type that can be directly used by the virtual machine. This process is called the class loading mechanism of the virtual machine. .

Class life cycle

A class starts from being loaded into the memory of the virtual machine to being unloaded from the memory. Its entire life cycle includes: loading, verification, preparation, analysis, initialization, use, and unloading. These 7 stages include verification, preparation, and analysis. These parts are collectively referred to as connections.

image-20200827153624097

The order of the five stages of loading, verification, preparation, initialization and unloading is determined. The loading process of the type must be started step by step in this order, while the parsing phase is not necessarily: it can be after the initialization phase in some cases To start again, this is to support the runtime binding feature of the Java language (also known as dynamic binding or late binding)

Note that the stages here are started in order, rather than being carried out or completed in order, because these stages are usually interleaved and mixed, and usually call or activate another stage during the execution of one stage.

Load: find and load the binary data of the class

During the loading phase, the virtual machine needs to complete the following 3 things:

  • 1) Obtain the binary byte stream that defines this class through the fully qualified name of a class.
  • 2) Convert the static storage structure represented by this byte stream into the runtime data structure of the method area.
  • 3) Generate a java.lang.Class object representing this class in memory as the access entry for various data of this class in the method area.

image-20200827112719502

Verification: to ensure the correctness of the loaded class

Verification is the first step in the connection phase. The purpose of this phase is to ensure that the information contained in the byte stream of the Class file meets the requirements of the current virtual machine and does not endanger the security of the virtual machine itself. The verification phase will roughly complete 4 phases of inspection actions:

  • File format verification: Verifies whether the byte stream conforms to the Class file format specification; for example: whether it 0xCAFEBABEstarts with, whether the major and minor version numbers are within the processing range of the current virtual machine, and whether the constants in the constant pool have unsupported types.
  • Metadata authentication: described bytecode information semantic analysis (Note: Comparative javacsemantic analysis phase of the compilation), which describes the information to ensure compliance with the requirements of the Java language specification; for example: whether a parent class, except java.lang.Objectthan .
  • Bytecode verification: Through data flow and control flow analysis, it is determined that the program semantics is legal and logical.
  • Symbol reference verification: to ensure that the parsing action can be executed correctly.

The verification phase is very important, but not necessary. It has no effect on the program runtime. If the referenced class has been repeatedly verified, you can consider using -Xverifynoneparameters to turn off most of the class verification measures to shorten the virtual machine class loading time.

Preparation: Allocate memory for static variables of the class and initialize them to default values

The preparation stage is the stage of formally allocating memory for the class variables and setting the initial value of the class variables. The memory used by these variables will be allocated in the method area .

Notes at this stage:

  • At this time, memory allocation includes only class variables (variables modified by static), not instance variables, which will be allocated in the Java heap along with the object when the object is instantiated.
  • Typically the initial value set here is the data type of the default value of zero (e.g. 0, 0L, null, falseetc.), rather than the values are given explicitly in Java code.

For example: Suppose a class variable is defined as public static int value = 3:; then the initial value of the variable value after the preparation phase is 0not 3, because no Java method has been executed yet, and the put staticinstruction to assign value to 3 is after the program is compiled. It is stored in the class constructor ()method, so the action of assigning value to 3 will be executed in the initialization phase.

  • For basic data types, for class variables (static) and global variables, if they are used directly without assigning them explicitly, the system will assign them a default zero value. For local variables, before use It must be assigned explicitly, otherwise it will not pass at compile time.

  • For constants that are staticboth finalmodified and modified at the same time , they must be explicitly assigned at the time of declaration, otherwise they will not be passed at compile time; while the constants that are only modified by final can be explicitly assigned at the time of declaration, or in The class is assigned a value explicitly when it is initialized. In short, it must be assigned a value explicitly before being used, and the system will not assign it a default zero value.

  • For reference data types reference, such as array references, object references, etc., if they are used directly without explicit assignment, the system will assign them the default zero value, ie null.

  • If no value is assigned to each element in the array when the array is initialized, the element will be assigned a default zero value according to the corresponding data type.

  • If the ConstantValue attribute exists in the field attribute table of the class field, which is modified by both final and static at the same time, the variable value will be initialized to the value specified by the ConstValue attribute in the preparation phase. Suppose the above class variable value is defined as: public static final int value = 3;Javac will generate ConstantValue property for value at compile time, and the virtual machine will assign value to 3 according to the ConstantValue setting during the preparation phase. We can understand that the static finalconstant puts its result into the constant pool of the calling class at compile time

Analysis: Convert symbolic references in the class to direct references

The resolution phase is the constant pool of the virtual machine process is replaced symbolic references directly referenced , mainly for the analysis operation , or 接口, 字段, 类方法, 接口方法, 方法类型, 方法句柄and 调用点qualifiers for symbolic references 7 classes. Symbol reference is a set of symbols to describe the target, which can be any literal.

直接引用It is a pointer that directly points to the target, a relative offset, or a handle indirectly positioned to the target.

Initialization: Perform initialization operations on static variables and static code blocks of the class

Initialization is to assign correct initial values ​​to the static variables of the class. The JVM is responsible for initializing the class, and mainly initializes the class variables. There are two ways to initialize class variables in Java:

  • Declaring class variables is to specify initial values
  • Use static code blocks to specify initial values ​​for class variables

Steps of class initialization

  • If this class has not been loaded and connected, the program first loads and connects the class
  • If the direct parent class of the class has not been initialized, the direct parent class is initialized first
  • If there are initialization statements in the class, the system executes these initialization statements in turn

When to trigger class initialization

Only when the active use of the class will lead to the initialization of the class, the active use of the class includes the following six types:

  • When using the new keyword to instantiate an object.

  • When reading or setting a type of static field (except for the static field that has been modified by final and the result has been put into the constant pool at compile time).

  • When calling a static method of a type.

  • When using the java.lang.reflect package method to make a reflection call on a type, if the type has not been initialized, its initialization needs to be triggered first.

  • When initializing a class, if you find that its parent class has not been initialized, you need to trigger the initialization of its parent class first.

  • When the virtual machine starts, the user needs to specify a main class to be executed (the class containing the main() method), and the virtual machine initializes the main class first.

The following situations will not perform class initialization

  1. Referencing the static fields of the parent class through the subclass will only trigger the initialization of the parent class, but not the initialization of the subclass.

  2. Defining an array of objects will not trigger the initialization of the class.

  3. Constants are stored in the constant pool of the calling class during compilation. Essentially, there is no direct reference to the class defining the constant, and the class
    where the constant is defined is not triggered .

  4. Obtaining the Class object by the class name will not trigger the initialization of the class.

  5. When loading the specified class through Class.forName, if the specified parameter initialize is false, the class initialization will not be triggered
    . In fact, this parameter tells the virtual machine whether to initialize the class.

  6. Through the default loadClass method of ClassLoader, the initialization action will not be triggered.

use

The interface of the data structure in the class access method area, the object is the data in the Heap area.

Uninstall

Several situations in which the Java virtual machine will end its life cycle

  • The System.exit() method is executed
  • The program ends normally
  • The program encountered an exception or error during execution and terminated abnormally
  • The Java virtual machine process is terminated due to an error in the operating system

Guess you like

Origin blog.csdn.net/kaihuishang666/article/details/108262783