What is a class loader? What is the Parental Delegation Model?

Insert image description here

  1. What is a class loader? What are the class loaders?
    If you want to understand the class loader, you must first understand the entire process of a Java file from compilation to execution. process. Insert image description here
    Class loader: used to load bytecode files (.class files)
    Runtime data area: used to allocate storage space
    Execution engine: execute bytecode files or local methods
    Garbage collector: used to recycle garbage content in the JVM
    1.1. Class loading JVM will only run binary files, and the main function of the class loader (ClassLoader) is to load bytecode files into the JVM so that the Java program can be started. Existing class loaders are basically subclasses of java.lang.ClassLoader. The only responsibility of this class is to find or generate the corresponding bytecode file for the specified class. At the same time, the class loader is also responsible for loading the program. Resources Required

1.2. Types of class loaders
Class loaders are divided into four types of class loaders based on their respective loading scopes:

Start the class loader (BootStrap ClassLoader):

This class does not inherit the ClassLoader class, which is written and implemented in C++. Used to load the class library in the JAVA_HOME/jre/lib directory.

Extended class loader (ExtClassLoader):

This class is a subclass of ClassLoader and mainly loads class libraries in the JAVA_HOME/jre/lib/ext directory.

Application class loader (AppClassLoader):

This class is a subclass of ClassLoader and is mainly used to load classes under classPath, that is, to load Java classes written by developers themselves.

Custom class loader:

Developer-defined classes inherit ClassLoader and implement custom class loading rules.

The hierarchical structure of the above three class loaders is as follows:
Insert image description here
The class loader system is not an "inheritance" system, but a delegation system. The class loader will first go to its own Search the class or resource in parent. If it cannot be found, it will search locally. The motivation for class loader delegation behavior is to avoid the same class being loaded multiple times.

  1. What is the Parental Delegation Model?
    If a class loader receives a request to load a class, it will not first try to load the class itself, but instead delegates the request task to the parent class loader to complete, in sequence. Recursively, if the parent class loader can complete the class loading task, it will return success; only when the parent class loader cannot complete the loading task, the next level will load it.
    Insert image description here
  2. Why does JVM use the parent delegation mechanism?
    The parent delegation mechanism can prevent a certain class from being loaded repeatedly. When the parent class has been loaded, there is no need to load it again to ensure uniqueness.

For security reasons, ensure that the class library API will not be modified.

Create a new java.lang package in the project, then create a new String class under the package and define the main function

public class String {
    
    

    public static void main(String[] args) {
    
    

        System.out.println("demo info");
    }
}

When the main function is executed at this time, an exception will occur. The main method cannot be found in the class java.lang.String.
Insert image description here
This message appears because of the parent delegation mechanism, java. lang.String is loaded in the Bootstrap classLoader because there is a class file with the same name in the core jre library, but there is no main method in the class. This prevents malicious tampering with the core API library.

  1. Execution process of class loading?
    A class starts from being loaded into the virtual machine until it is unloaded. Its entire life cycle includes: loading, verification, preparation, parsing, initialization, use and unloading. Among them, the three parts of verification, preparation and parsing are collectively called linking.
    Insert image description here
    Detailed explanation of the class loading process

1. Load
Insert image description here
Obtain the binary data stream of the class through the full name of the class.

Parse the binary data stream of the class into the data structure in the method area (Java class model)

Creates an instance of the java.lang.Class class to represent this type. As the access entrance to various data of this class in the method area
Insert image description here
2. Verification
Insert image description here
Verify whether the class complies with JVM specifications and security check

(1) File format verification: Whether it meets the specifications of the Class file

(2) Metadata verification

Does this class have a parent class (except for the Object class, all other classes should have parent classes)

Whether this class inherits (extends) a class modified by final (a class modified by final means that the class cannot be inherited)

Whether the fields and methods in the class conflict with the parent class. (Methods or fields modified by final cannot be overridden)

(3) Bytecode verification - The main purpose is to determine that the program semantics are legal and logical through the analysis of data flow and control flow.

(4) Symbol reference verification: A symbol reference uses a set of symbols to describe the referenced target. The symbols can be any form of literals.

For example: int i = 3; Literal: 3 Symbol reference: i

3. Preparation
Insert image description here
Allocate memory for class variables and set initial values ​​of class variables

static variables, the allocation of space is completed in the preparation phase (default value is set), and the assignment is completed in the initialization phase

Static variables are the basic type of final, as well as string constants. The value has been determined and the assignment is completed in the preparation phase.

The static variable is a final reference type, so the assignment will also be completed during the initialization phase
Insert image description here
4. Parsing
Insert image description here
Convert the symbol reference in the class to direct quote

For example: if other methods are called in the method, the method name can be understood as a symbolic reference, and a direct reference means using a pointer to point directly to the method.
Insert image description here
5. Initialization
Insert image description here
Perform initialization operations on static variables and static code blocks of the class

If a class is initialized and its parent class has not yet been initialized, its parent class will be initialized first.

If multiple static variables and static code blocks are included at the same time, they will be executed in top-down order.

6. Use
Insert image description here
JVM to start executing the user's program code from the entry method

Call static class member information (such as: static fields, static methods)

Use the new keyword to create an object instance for it

7.Uninstall

When the user program code is executed, the JVM begins to destroy the created Class object, and finally the JVM responsible for running it also exits the memory.

5. Class loader interview
Interviewer: What is a class loader and what are the class loaders?

candidate:

The JVM will only run binary files, and the main function of the class loader (ClassLoader) is to load bytecode files into the JVM so that the Java program can be started.

There are 4 common class loaders

The first one isBootStrap ClassLoader: It is written and implemented in C++. Used to load the class library in the JAVA_HOME/jre/lib directory.

The second one isExtension Class Loader (ExtClassLoader): This class is a subclass of ClassLoader and mainly loads JAVA_HOME/jre/lib Class libraries in the /ext directory.

The third one isApplication Class Loader (AppClassLoader): This class is a subclass of ClassLoader and is mainly used to load files under classPath Class, that is, loading Java classes written by developers themselves.

The fourth is the custom class loader: the developer's custom class inherits ClassLoader and implements custom class loading rules.

Tell me about the execution process of class loading?

From the time a class is loaded into the virtual machine until it is unloaded, its entire life cycle includes seven stages: loading, verification, preparation, parsing, initialization, use and unloading. Among them, the three parts of verification, preparation and parsing are collectively called linking.

1. Loading: Find and import class files

2. Verification: Ensure the accuracy of loaded classes

3. Preparation: Allocate memory for class variables and set initial values ​​of class variables

4. Parsing: Convert symbol references in the class into direct references

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

6. Use: JVM starts executing the user's program code from the entry method

7. Unloading: When the user program code is executed, the JVM begins to destroy the created Class object, and finally the JVM responsible for running it also exits the memory.

What is the Parental Delegation Model?

If a class loader receives a class loading request, it will not try to load the class itself first, but delegates the request to the parent class loader to complete. This is true for every level of class loader, so all The load request should eventually be passed to the top-level startup class loader. Only when the parent class loader returns that it cannot complete the load request (the required class is not found in its search return), the child class loader will try Load it yourself

Why does JVM use parent delegation mechanism?

There are two main reasons.

First, the parent delegation mechanism can prevent a certain class from being loaded repeatedly. When the parent class has been loaded, there is no need to load it repeatedly to ensure uniqueness.

Second, for security reasons, ensure that the class library API will not be modified.

Guess you like

Origin blog.csdn.net/weixin_45817985/article/details/134859354