Case explanation of loading mechanism such as Java

Time:2021-9-24

1. Class loading

<1> . the order in which parent and child classes are executed

1. Static variables and static code blocks of the parent class (writing order)

2. Static variables and static code blocks of subclasses (writing order)

3. Instance code block of parent class (writing order)

4. Member variables and construction methods of parent class

5. Instance code block of subclass

6. Member variables and construction methods of subclasses

<2> Class loading timing

If the class is not initialized, it needs to be initialized first. The virtual machine specification strictly stipulates that there are only five cases in which the class must be initialized first (while loading, verification and preparation should start before this)

1. Create an instance of a class (new method), access the static variable of a class, or assign a value to the static variable, and call the static method of the class

2. Reflection mode

3. If you initialize a subclass of a class, its parent class will also be initialized

4. When the Java virtual machine is started, the class marked as the startup class is a main class (such as the main class) that directly uses java.exe to run

5. When using the dynamic language support of jdk1.7

<3> Class lifecycle

Seven stages: loading, validation, preparation, parsing, initialization, use and unloading. The three parts of verification, preparation and parsing are called connections

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CicgRzZ9-162(file:///C:/Users/26905/Desktop/%E6%AF%94%E7%89%B9%E8%AF%BE%E4%BB%B6/%E7%B1%BB%E5%8A%A0%E8%BD%BD_files/Image.png)]

In some cases, the parsing phase can be performed after the initialization phase to support runtime binding (dynamic binding) of the Java language

<4> Class loading process

Next, let’s explain in detail the whole process of class loading in Java virtual machine, that is, the specific actions performed in the five stages of loading, validation, preparation, parsing and initialization.

1. Loading

<1> Get the binary byte stream that defines a class by its fully qualified name.

<2> The static storage structure represented by this byte stream is transformed into the runtime data structure of the method area.

<3> A Java. Lang. class object representing this class is generated in memory as an access to various data of this class in the method area.

2. Verification

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 will not endanger the security of the virtual machine itself.

3. Preparation

The preparation phase is formalClass variableAllocate memory and set class variablesInitial valueThe memory used by these variables will be allocated in the method area.

Suppose a class variable is defined as:


public static int value=123;

The initial value of the variable value after the preparation stage is 0 instead of 123, because no Java method has been executed at this time, and the putstatic instruction that assigns value to 123 is compiled and stored in the class constructor () method, so the action of assigning value to 123 will be executed in the initialization stage.

4. Analysis

The process by which a virtual machine replaces a symbolic reference in a constant pool with a direct reference.

Symbol reference: the symbol reference has nothing to do with the memory layout implemented by the virtual machine, and the target of the reference may not have been loaded into memory.

Direct reference: direct reference is related to the memory layout of the virtual machine implementation. If there is a direct reference, the target of the reference must already exist in memory.

5. Initialization

In the preparation phase, the variable has been assigned the initial value required by the system once. In the initialization phase, class variables and other resources are initialized according to the subjective plan formulated by the programmer through the program, or it can be expressed from another perspective: the initialization phase is the process of executing class constructor () methods.

Understand:

() method is generated by the combination of the assignment action of all class variables in the compiler’s automatic collection class and the statements in the static statement block (static {} block). The compiler’s collection order is determined by the order of statements in the source file. In the static statement block, only variables defined before and after the static statement block can be accessed, The previous static statement block can be assigned, but cannot be accessed:

public class Test{
    static{
        i=0; // Assigning values to variables can be compiled normally
        System.out.print(i); // The compiler will prompt "illegal forward reference"
    }
    static int i=1;
}

1. () method(Construction method of class)Unlike the class constructor (or instance constructor () method), it does not need to explicitly call the parent class constructor. The virtual opportunity ensures that the parent class () method has been executed before the subclass () method is executed. Therefore, the class of the first () method to be executed in the virtual machine must be java.lang.object.

2. The () method is not necessary for a class or interface. If there is no static statement block in a class and no assignment operation on variables, the compiler may not generate () methods for this class.

3. The interface is initialized only when the variables defined in the interface are used: static statement blocks cannot be used in the interface, but there are still assignment operations for variable initialization, so the interface will generate () methods like classes. However, the difference between an interface and a class is that the () method of the interface does not need to execute the () method of the parent interface first. The parent interface is initialized only when the variables defined in the parent interface are used. In addition, the implementation class of the interface will not execute the () method of the interface during initialization.

4. Virtual opportunity ensures that the () method of a class is correctly locked and synchronized in a multithreaded environment. If multiple threads initialize a class at the same time, only one thread will execute the () method of this class, and other threads need to block and wait until the active thread finishes executing the () method. If there is a time-consuming operation in the () method of a class, it may cause multiple process blocking, which is often hidden in practical applications.

<5> Class loader

Class loader can be divided into startup class loader, extension class loader, application class loader and custom class loader. Their relationship is generally as follows:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sVRciBVN-1627452314592)(C:\Users\26905\AppData\Roaming\Typora\typora-user-images\image-20210728134416563.png)]

1. Start the class loader (bootstrap classloader)
This class is implemented by C + + language and is a part of the virtual machine itself. It does not inherit classloader and cannot operate it. Used to load the core classes of Java.

2. Extension class loader (extclassloader)
This class loader is implemented in Java code in the class sun. Misc. Launcher $extclassloader. It is responsible for loading < Java_ All class libraries in the home > \ lib \ ext directory or in the path specified by the java.ext.dirs system variable.

3. Application class loader (appclassloader)
It is responsible for loading the – classpath or – CP option from the Java command, the jar package and classpath specified by the java.class.path system attribute when the JVM starts. In the application code, you can get the application class loader through the static method getsystemclassloader () of classloader. If not specified, all user-defined classes will be loaded by the custom class loader without using the custom class loader.

4.2 custom loader
If the user has customized the class loader, all the custom class loaders take the application class loader as the parent loader. The parent class loader of the application class loader is the extension class loader. These class loaders are hierarchical. The boot loader is also called the root loader and is the parent loader of the extension loader

<6> Class loading mechanism — parental delegation model

Process of parent delegation model: if a class loader receives a class loading request, it will not try to load the class itself, but delegate the request to the parent class loader to complete it. This is true for class loaders at each level, so all loading request information will eventually be transmitted to the top-level startup class loader, Only when the parent loader reports that it cannot complete the load request (that is, its search scope does not find the required class), the child loader will try to complete the load by itself

Find first and then load

(1) Look from bottom to top

(2) Load from top to bottom

Benefits of parental delegation model: parental delegation model is very important for the stable operation of Java programs

Disadvantages: unable to meet the flexible class loading method. (solution: Rewrite loadclass and destroy the parental delegation model, such as SPI mechanism)

This is the end of this article on the case explanation of loading mechanisms such as Java. For more relevant loading contents such as Java, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

A detailed explanation of the differences between Perl and strawberry Perl and ActivePerl

Perl is the abbreviation of practical extraction and report language “practical report extraction language”. Application of activestateperl and strawberry PERL on Windows platformcompiler。 Perl   The relationship between the latter two is that C language and Linux system have their own GCC. The biggest difference between activestate Perl and strawberry Perl is that strawberry Perl […]