当前位置:网站首页>[JVM] class loading mechanism
[JVM] class loading mechanism
2022-06-11 00:11:00 【Xiangge learns big data】
Catalog
2. The process of class loading
Java What is the class loading mechanism
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
边栏推荐
- 【漫天烟花】绚烂烟花点亮夜空也太美了叭、某程序员携带烟花秀给大家拜年啦~
- 【Turtle表白合集】“海底月是天上月,眼前人是心上人。”余生多喜乐,长平安~(附3款源码)
- Pseudo static setting of Typecho - starze V Club
- 【自动回复小脚本】新年快乐,每一个字都是我亲自手打的,不是转发哦~
- [pyGame games] story stream recommendation: what kind of games can you like? (devil lover, bully's wife version)
- Basic introduction and core components of kubernetes
- [pyGame games] tank battle, how many childhood games do you remember?
- Leetcode-209 minimum length subarray
- Wireshake introduction learning notes
- 【AI出牌器】第一次见这么“刺激”的斗地主,胜率高的关键因素竟是......
猜你喜欢

【自动回复小脚本】新年快乐,每一个字都是我亲自手打的,不是转发哦~

Bluetooth (5) -- about retransmission

From the perspective of Confucius Temple IP crossover, we can see how the six walnuts become "butterflies" for the second time

【Opencv实战】这个印章“神器”够牛,节省了时间提高了效率,厉害~(附完整源码)

Bluetooth development (3) -- look at the air bag
![[pyGame] can the little dinosaur on chrome be played with code? It looks like fun~](/img/b4/a4140eb10658af40a8a2fc0f428b0f.jpg)
[pyGame] can the little dinosaur on chrome be played with code? It looks like fun~

LabVIEW displays the time and date on the waveform chart or waveform chart

A simple understanding of B tree
![[pyGame games] I'm not afraid you can't walk the maze series: the ultimate AI walks the maze. After learning, it will take you to open the door to a new world ~ (with game source code)](/img/57/dcf291b044b5e5860a7fdc817076d5.jpg)
[pyGame games] I'm not afraid you can't walk the maze series: the ultimate AI walks the maze. After learning, it will take you to open the door to a new world ~ (with game source code)
![[pyGame games] tank battle, how many childhood games do you remember?](/img/30/951fdbb944e026701af08c0c068cd8.png)
[pyGame games] tank battle, how many childhood games do you remember?
随机推荐
IGBT and third generation semiconductor SiC double pulse test scheme
[MVC&Core]ASP.NET Core MVC 视图传值入门
Is the financial management of qiniu school reliable and safe
Read it once: talk about MySQL master-slave
[pyGame] stir up your brain and play the "24 o'clock" idea together ~ (awesome)
[turtle confessions collection] "the moon at the bottom of the sea is the moon in the sky, and the person in front of us is the sweetheart." Be happy for the rest of your life, and be safe for ever ~
sql 语句--输入 月份 查日期(年月日),输出 月份
关于优化API接口响应速度
MySQL command line import and export data
curl导入postman报错小记
【AcWing】4. Multiple knapsack problem I
【颜值检测神器】来,请拿出你们的绝活(这颜值,对得起观众么?)
Merge sort
Typecho blog site wide deployment of Tencent cloud CDN tutorial - Xingze V Club
Why is the website snapshot hijacked and tampered with
快速排序
Pseudo static setting of Typecho - starze V Club
Top ten information security principles
Leetcode-15 sum of three numbers
都说验证码是爬虫中的一道坎,看我只用五行代码就突破它。