当前位置:网站首页>Talking about JVM 4: class loading mechanism
Talking about JVM 4: class loading mechanism
2022-07-05 00:49:00 【QinGeneral】
In the previous article, we learned how to read the bytecode and the runtime stack frame structure in the bytecode execution engine , The method calls in bytecode execution engine have not been covered .Java The polymorphic characteristics of Chinese are inseparable JVM Dynamic binding of , Dynamic binding technology is the key to method dynamic invocation . And if you want to introduce the method calling mechanism , You need to know the bytecode in JVM The life cycle process from load to unload .
The bytecode is JVM From load to unload , Through the following process .
We now know how to read outside class The structure of bytecode , And part of the runtime . The former belongs to “ load ” Previous content , The latter belongs to “ Use ” Stage . This time we will take a look at the process from loading to using , This is it. JVM Class loading mechanism of .
There are many ways to input external bytecode , For example, local class file 、 Network byte stream 、 Bytecode content generated by the program .
Java Virtual machine will be external class Bytecode loaded into memory , It needs to be loaded 、 link 、 Three phases of initialization .
Before you understand the class loading mechanism , Let's start with a brief review JVM Division of logical areas . Include 5 part :
- Method area
- Java Pile up
- Program counter
- Java Stack
- Native Method Stack
load
The loading phase is mainly responsible for reading the external byte stream , Convert the storage structure of byte stream into runtime data structure , Store in method area . At the same time Java Create corresponding classes in the heap java.lang.Class object , As the access to method area data . At this time, the runtime data structure in the method area is implemented by virtual machines .
Except that the byte stream of array class is directly generated by the virtual machine , Other classes are loaded mainly by ClassLoader complete .ClassLoader There is a boot class loader 、 Extend the classloader 、 Apply the class loader , Its structure conforms to the parental delegation model , It means that the subclass loader needs to be loaded by the parent class loader before loading the class , Such layers of transmission , If the parent class does not handle it, it will be handed over to the child class .
The boot class loader consists of C++ To write , No, Java object . Extend the classloader 、 Application class loaders are java.lang.ClassLoader Subclass , Need to be loaded by other classes , Such as starting class loader , Loading in .
The boot class loader is mainly responsible for loading the most basic 、 Important classes , Such as JRE Next lib In the directory jar package . The extension class loader is responsible for loading JRE Next lib/ext General in the directory 、 The extension class . The application class loader mainly loads the classes under the application path .
The parental delegation model ensures the security and uniqueness of the class loading process , Because any subclass loader ( Including the class loader implemented by the developer ) Before loading the class , You need to hand over the class to the parent class loader first . On the one hand, this ensures the division of loading functions of different attribute classes , such as Object Classes are always loaded by the boot class loader , This allows no matter which class loader is loaded Object, This class can guarantee the same and unique . On the other hand , This ensures the security of class loading , Developers cannot forge things like java.lang.Object Wait for basic classes to cheat JVM, Because of the built-in ClassLoader Relevant safety verification work has been done .
It should be noted that , If the same bytecode is loaded by different class loading instances , You get two different classes .
Java 9 Modular support for ClassLoader Some modifications have been made , I will not go into details here .
link
The link phase is divided into verification 、 Get ready 、 Analyze three stages .
Validation phase
The verification phase is mainly responsible for verifying whether the bytecode loaded in the previous step conforms to the specification , Ensure that it will not harm JVM The safety of the . This step is an important guarantee for program safety , The work at this stage also accounts for a considerable proportion in the whole class loading process , Mainly including byte code format 、 grammar 、 Semantic verification .
Preparation stage
The preparation phase is mainly responsible for allocating memory for static fields in the class , And initialized to zero . At this time, only memory will be allocated to class variables , stay JDK 8 And after , Class variables will be stored in Class Where the object is located Java Allocate in the heap . The memory allocation of instance variables should wait until the object is instantiated .
Analytic stage
The parsing phase is the process of converting symbolic references in the constant pool into direct references .
When we learned to read bytecode , Constants of the constant pool are represented by indexes , The reference relationship between constants 、 Method bytecode obtains variables and other operations through reference index , These indexes are called symbolic references . Symbolic reference only expresses the logical reference relationship between variables , And the actual runtime variables 、 The memory location of the method is not fixed , So before running bytecode , These symbolic references need to be resolved into pointers to the target 、 Offset or handle , This is related to the specific memory layout of the runtime .
Of course , The parsing phase did not complete the parsing process of all symbol references , For classes or interfaces 、 Field 、 Class method 、 The parsing of interface methods can be completed at this stage . But for method types 、 The resolution of method handles and call point qualifiers is closely related to the feature support of dynamic languages , It will not be completed at this stage . This is because the specific method corresponding to the method call has not been determined at this time , It can't be determined until it is actually implemented .
initialization
The initialization phase is the beginning when the virtual machine starts executing the application code , It's the execution class constructor <clinit>
Method process . The method by Javac Compile time , By collecting class variable assignment statements and static Code blocks are merged to produce .
As follows Java Code and its corresponding <clinit>
Bytecode as an example , It can be found that class constructors only deal with class variables and content in static code blocks , Ignore instance variables .
// java
private static int a = 100;
static {
a = 1000;
}
private int mThisIsInt = 1024;
// bytecode
bipush 100
putstatic #28 <Demo.a : I>
sipush 1000
putstatic #28 <Demo.a : I>
return
Here we can mention the implementation of static inner class singleton pattern .
public class Singleton {
private Singleton() {
}
private static class Holder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
Inner class Holder
The initialization time of is when the static field of this class is called , Now trigger <clinit>
Method call , Then create a singleton object .JVM When this method is called, it will be locked , Ensure that the method will be called only once . This feature ensures the delayed loading of singletons and the safety of multithreading .
summary
This time we have mastered JVM The three stages of the class loading process : load 、 link 、 initialization .JVM Logically, it is divided into method areas 、Java Pile up 、 Program counter 、Java Stack 、 Native Method Stack . Method area and Java Heap is mainly used to store data , Including byte code corresponding data structure and runtime object . Other parts are mainly responsible for runtime method calls 、 Computing and other functions .
After understanding the class loading mechanism 、JVM After logical region division and execution of runtime stack frame and method bytecode , Next time we have time to talk about how calls between methods happen .
边栏推荐
- Sorting selection sorting
- Five papers recommended for the new development of convolutional neural network in deep learning
- P4281 [AHOI2008]紧急集合 / 聚会(LCA)
- Identifiers and keywords
- Distributed base theory
- What if the programmer's SQL data script coding ability is weak and Bi can't do it?
- Expose testing outsourcing companies. You may have heard such a voice about outsourcing
- Huawei employs millions of data governance experts! The 100 billion market behind it deserves attention
- Get to know ROS for the first time
- It's too convenient. You can complete the code release and approval by nailing it!
猜你喜欢
2022.07.03 (lc_6111_counts the number of ways to place houses)
基本放大电路的学习
[paper reading] cavemix: a simple data augmentation method for brain vision segmentation
Operator explanation
IT转测试岗,从迷茫到坚定我究竟付出了什么?
uniapp微信小程序拿来即用的瀑布流布局demo2(方法二)(复制粘贴即可使用,无需做其他处理)
P3304 [sdoi2013] diameter (diameter of tree)
[paper reading] Tun det: a novel network for meridian ultra sound nodule detection
Innovation leads the direction. Huawei Smart Life launches new products in the whole scene
【C】 (written examination questions) pointer and array, pointer
随机推荐
Upload avatar on uniapp
URL和URI
【C】 (written examination questions) pointer and array, pointer
Date time type and format in MySQL
有哪些收益稳定的理财产品,这两个都不错
[论文阅读] TUN-Det: A Novel Network for Thyroid Ultrasound Nodule Detection
Two numbers replace each other
Specification for fs4061a boost 8.4v charging IC chip and fs4061b boost 12.6V charging IC chip datasheet
2022.07.03 (LC 6109 number of people who know secrets)
7. Scala process control
两个数相互替换
Acwing164. Accessibility Statistics (topological sorting +bitset)
const、volatile和restrict的作用和用法总结
[Yocto RM]11 - Features
Verilog tutorial (11) initial block in Verilog
Five papers recommended for the new development of convolutional neural network in deep learning
It's too convenient. You can complete the code release and approval by nailing it!
Some basic functions of enterprise projects are developed, and important things are saved to online first a
Netcore3.1 JSON web token Middleware
skimage: imread & imsave & imshow