当前位置:网站首页>[JVM] class loading mechanism

[JVM] class loading mechanism

2022-06-11 00:11:00 Xiangge learns big data

Catalog

 

 

1. Class load time

2. The process of class loading

2.1 load

2.2 verification

2.3 Get ready

2.4 analysis

2.5 initialization

3. Frequently asked questions

Java What is the class loading mechanism

Parent delegation model

Break the parental delegation model

Class.forName() and ClassLoader.loadClass() The difference between


 

1. Class load time

Loading time refers to the time when the first stage loading occurs

1). encounter new( use new Instance object ),getStatic( Read a static field ),putstatic( Set a static field ),invokeStatic( Call a static method of a class ) These four instruction bytecode commands

2). Use Java.lang.reflect When a package's method makes a reflection call on a class , If the class does not perform init, Will first init.

3). When initializing a class , If its parent class is not initialized , Initialize the parent class first

4).jvm Startup time , The user needs to specify a main class to execute ( contain main Class ) The virtual opportunity executes this class first

5). When using JDK1.7 Dynamic language support , When java.lang.invoke.MethodHandler The result of the example is REF-getStatic/REF_putstatic/REF_invokeStatic The handle of , And if the classes corresponding to these handles are not initialized, they should be initialized first .

6). When an interface defines JDK8 New default method added (default), If the implementation class of this interface is initialized , Then the interface should be initialized before it

2. The process of class loading

2.1 load

Purpose

1) Get the binary byte stream that defines this class through the fully qualified class name of a class

2) Stream this byte in Represents the static storage structure ( That is to say static Identified method constants, etc ) Translational site Method area The runtime data structure of

3) Generate a representation of this class in memory java.lang.class object , As the of various data of this class in the method area Access portal

Add : In the loading phase, the action of getting the binary byte stream of the class is the most controllable phase for developers , Generally speaking, it is by jvm Built in boot class loader to complete , Class loaders can be overridden to control how byte streams are obtained

2.2 verification

Purpose

1) This step is Make sure Class The information contained in the byte stream of the file conforms to 《java Virtual machine specification 》 All the constraints of

Add :1. It is important to verify this step , Protect virtual machines from malicious code attacks , This step consumes a considerable amount of code and performance time in the whole process of class loading

2. Check the action : File format validation : Including coding format ,class Whether the version number of the file conforms to the current jvm, Main purpose Is to verify whether the byte stream can exist in the method area , The next three steps are to verify that there will be no byte stream read / write operations in the method area

                  Metadata validation Guarantee that there is no relationship between 《java language norm 》 Metadata information that does not conform to the definition ( For example, this class is not an abstract class. Does it implement all the methods required by the parent class )

                  Bytecode verification   Class methods Ensure that the method does not do anything harmful to the virtual machine while it is running

                  Symbol reference validation class , Whether field methods can be accessed (private protected)

2.3 Get ready

Purpose

1) Formally define variables in the class ( Here it means static Decorated variable ) Allocate memory And set the class variable initialization stage

Add : For example, there is such a line of code in the class public static int value = 123; Then after the preparation stage is completed, it will be value Initialize and assign 0, The assignment operation is not executed until initialization , This is just initialization memory

 

2.4 analysis

Purpose

1) The process of replacing a symbolic reference in a constant pool with a direct reference ( Recursively find whether the parent class has a method that matches the target , Until I find java.lang.Object)

With class or interface parsing 、 Field analytical 、 Method parsing and interface method parsing

 

2.5 initialization

Purpose

To actually execute the program , Do initialization assignment ( That is, in the class Java Code ). for example 2.3 Examples prepared in , This step is about 123 The value of is attached to value Static variables are loaded

 

3. Frequently asked questions

Java What is the class loading mechanism

Above

Parent delegation model

The parental delegation model requires In addition to the top-level boot loader , The rest of the class loaders should have their own parent class loaders , Please note that the parent-child relationship in the two parent delegation mode is not what is commonly referred to as class inheritance , It is Reuse the related code of the parent class loader by using the composition relationship , The relationship between class loaders is as follows :

The parent delegation model is Java 1.2 After the introduction of , It works by , If a class loader receives a class load request , It doesn't load itself first , Instead, the request is delegated to the loader of the parent class , If the parent loader still has its parent loader , Then further entrust , Recursion in turn , The request will eventually reach the top-level boot loader , If the parent loader can complete the class loading task , Just Successfully returns , If the parent loader cannot complete this load task , Sub loader will try to load by itself , This is the parent delegation model ( Recursion up and recursion down )


Parents' delegation chart :  https://blog.csdn.net/codeyanbao/article/details/82875064

 

Break the parental delegation model

As mentioned above, the parental delegation model is not a mandatory constraint model , It is java The implementation of classloader recommended by the designer to the developer , stay java Most of the world's classloaders follow this model , But there are exceptions , up to now , There have been three large-scale parent assignment models “ Be destroyed ” situation .

1. The first time a parent delegation model “ Be destroyed ” In fact, it happened before the emergence of the parental delegation model -- namely JDK1.2 Before release . Because the parental delegation model is in JDK1.2 It was introduced later , And class loaders and abstract classes java.lang.ClassLoader It is JDK1.0 It's already there , Facing the existing user-defined class loader implementation code ,Java Designers have to make some compromises when they introduce the parental delegation model . For forward compatibility ,JDK1.2 After that java.lang.ClassLoader Added a new proceted Method findClass(), Before that , Users inherit java.lang.ClassLoader The only purpose of this is to rewrite loadClass() Method , Because the private method of the loader will be called when the virtual class is loaded loadClassInternal(), The only logic of this method is to call its own loadClass().JDK1.2 After that, users are no longer encouraged to cover loadClass() Method , You should write your own class loading logic to findClass() In the method , stay loadClass() In the logic of the method , If the parent loader fails to load , Will call your own findClass() Method to complete the load , In this way, we can ensure that the newly written class loader conforms to the parental delegation model .
2. The second time of the parent delegation model “ Be destroyed ” It's a defect of the model itself , The parental delegation model solves the problem of unifying the basic classes of each class loader ( The more basic class is loaded by the higher loader ), The basic class is called “ Basics ”, Because they are always called as called code API. however , If the base class calls the user's code again , So what should we do ?
It's not impossible , A typical example is JNDI service ,JNDI Now it is Java Standard services , Its code is loaded by the boot loader ( stay JDK1.3 Put in when rt.jar), but JNDI The purpose is to manage and search resources in a centralized way , It needs to call the independent vendor implementation Department deployed in the application classpath Under the JNDI Interface provider (SPI, Service Provider Interface) Code for , But starting a classloader is not possible “ know ” Some of the code , What should I do ?
To solve this dilemma ,Java The design team had to introduce a less elegant design : Thread up and down file class loader (Thread Context ClassLoader). This class loader can be used through java.lang.Thread Class setContextClassLoader() Method to set , If the thread is not set when it is created , It will inherit a... From the parent thread ; If it is not set in the global scope of the application , Then this class loader is the application class loader by default . With thread context class loader ,JNDI The service uses this thread context class loader to load what it needs SPI Code , In other words, the parent class loader asks the child class loader to complete the class loading action , This behavior is actually to break through the hierarchy of the parent delegation model to use the classloader in reverse , Has violated the parental delegation model , But it is also a matter of helplessness .Java All of them involve SPI The loading action of is basically in this way , for example JNDI,JDBC,JCE,JAXB and JBI etc. .
3. The third time the parent delegation model “ Be destroyed ” It is due to the user's pursuit of the dynamic nature of the program , for example OSGi Appearance . stay OSGi In the environment , The classloader is no longer a tree in the parental delegation model , It's a network structure .

 

Class.forName() and ClassLoader.loadClass() The difference between


Class.forName(className) Method , The method actually called inside is  Class.forName(className,true,classloader);
The first 2 individual boolean Parameter indicates whether the class needs to be initialized ,  Class.forName(className) The default is initialization .
Once initialized , Will trigger the target object's static Block code execution ,static Parameters will also be initialized again .   

ClassLoader.loadClass(className) Method , The method actually called inside is  ClassLoader.loadClass(className,false);
The first 2 individual boolean Parameters , Indicates whether the target object is linked ,false Means no link , You can ,
Not linking means not doing some column steps including initialization , Then static blocks and static objects will not be executed

 

原网站

版权声明
本文为[Xiangge learns big data]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206102253040964.html