当前位置:网站首页>Loading process of [JVM series 3] classes
Loading process of [JVM series 3] classes
2022-06-13 03:08:00 【Louzai】

Mainly about Java Class loading process .
Previous selections ( Welcome to forward ~~)
How to treat programmers 35 Career crisis at the age of 20 ?
Java A complete set of learning materials (14W word ), It took half a year to sort out
I've had liver for three months , Wrote for you GO Core manual
Message queue : From selection to principle , One article will take you all to master
Liver for a month ETCD, from Raft From principle to practice
Preface
In fact, the class loading process should be put into JVM The first series of , Because I touch JVM It's from JVM Memory structure starts , So let's go through 2 This article completes the explanation of this content . about Java Class loading process , I don't think there's much in it , It's not that important , Just sort out the information on the Internet , As an understanding, you can .
brief introduction
If JVM Want to execute this .class file , We need to put it into a class loader in , It's like a porter , Will take all of .class All documents moved in JVM Come inside .

Key knowledge :
Java The file is compiled to .class Bytecode file
Bytecode files are moved to... Via classloader JVM In the virtual machine
Virtual machine main 5 large : Method area , Heap is thread shared area , There are thread safety issues , Stacks and local method stacks and counters are exclusive areas , There is no thread safety issue , and JVM The tuning of is mainly around the heap , Stack two blocks .

Class loading process
Class loading includes loading 、 verification 、 Get ready 、 analysis 、 Initialize five stages . In these five stages , load 、 verification 、 The order in which these four phases occur is determined , The parsing phase is not necessarily , It can start after the initialization phase in some cases , This is to support Java Language runtime binding ( Also called dynamic binding or late binding ). Also note that the stages here are sequential , Not in sequence or complete , Because these stages are usually mixed with each other , It usually calls or activates another stage in the execution of a phase .

load
Find and load the binary data of a class, the first stage of the class loading process , In the loading phase , There are three things virtual machines need to do :
Get the binary byte stream defined by the fully qualified name of a class .
Convert the static storage structure represented by the byte stream into the runtime data structure of the method area .
stay Java Generate a java.lang.Class object , As an access to the data in the method area .
verification
Make sure the class being loaded is correct
Verification is the first step in the connection phase , The purpose of this phase is to ensure Class The information contained in the byte stream of the file meets the requirements of the current virtual machine , And will not endanger the security of virtual machine itself . The validation phase is roughly complete 4 Three stages of test action :
File format validation : Verify that the byte stream matches Class Specification of document format ; for example : Whether or not to 0xCAFEBABE start 、 Whether the primary and secondary version numbers are within the processing range of the current virtual machine 、 Whether constants in constant pool have unsupported types .
Metadata validation : Semantic analysis of information described by bytecode ( Be careful : contrast javac Semantic analysis in compilation phase ), In order to ensure that the information described in it conforms to Java The requirements of language norms ; for example : Does this class have a parent class , except java.lang.Object outside .
Bytecode verification : Through data flow and control flow analysis , Make sure the program semantics are legal 、 Logical .
Symbol reference validation : Make sure that the parsing action performs correctly .
Get ready
Allocate memory for static variables of a class , And initialize it to the default value
The preparation stage is the stage of formally allocating memory for class variables and setting the initial value of class variables , All of this memory will be allocated in the method area . There are several points to pay attention to in this stage :
At this time, memory allocation only includes class variables (static), Not instance variables , Instance variables will be allocated along with a block of objects when they are instantiated Java In the pile .
The initial value set here is usually the default zero value of the data type ( Such as 0、0L、null、false etc. ), Instead of being in Java The value in the code that is explicitly assigned .
If there is... In the field property table of a class field ConstantValue attribute , At the same time final and static modification , So in the preparation stage variables value It will be initialized to ConstValue The value specified by the property .
Suppose a class variable is defined as :publicstaticintvalue=3, So variable value The initial value after the preparation phase is 0, instead of 3, Because at this time, we haven't started any Java Method ,value The assignment is 3 The action will not be executed until the initialization phase .
analysis
Convert symbolic references in a class to direct references
In the parsing phase, the virtual machine replaces the symbolic reference in the constant pool with the direct reference , Parsing actions are mainly for classes or interfaces 、 Field 、 Class method 、 Interface method 、 Method type 、 Method handle and call point qualifier 7 Class symbol reference . Symbol reference is a set of symbols to describe the target , It can be any literal amount . A direct reference is a pointer directly to the target 、 Relative offset or an indirect handle to the target .
initialization
Initialization is actually an assignment operation , It executes a method of a class constructor . The compiler automatically collects the assignment actions of all variables in the class , The one in the preparation stage static int a = 3 Example , At this time, it is officially assigned as 3
uninstall
GC Unload useless objects from memory ,Java The virtual machine will end its life cycle :
Yes System.exit() Method
The normal execution of the program ends
The program encountered an exception or error during execution and terminated abnormally
Caused by an error in the operating system Java Virtual machine process termination
Loading order of class loader
Load one Class The order of classes also has priority , The order of class loaders from the bottom up is as follows :
BootStrap ClassLoader:rt.jar
Extention ClassLoader: Load extended jar package
App ClassLoader: designated classpath Below jar package
Custom ClassLoader: Custom class loader

Parent delegate mechanism
The workflow of the parent delegation model is : If a class loader receives a class load request , It doesn't try to load the class itself first , Instead, the request is delegated to the parent loader to complete , One by one , therefore , All class loading requests should eventually be passed to the top-level boot class loader , Only if the parent loader does not find the required class in its search scope , That is, the load cannot be completed , The child loader will try to load the class by itself .
Parent delegate mechanism :
When AppClassLoader Load one class when , It doesn't try to load the class itself first , Instead, delegate the class load request to the parent loader ExtClassLoader To complete .
When ExtClassLoader Load one class when , It doesn't try to load the class itself first , Instead, delegate the class load request to BootStrapClassLoader To complete .
If BootStrapClassLoader Loading failed ( For example, in $JAVA_HOME/jre/lib We didn't find the class), Will use ExtClassLoader To try to load ;
if ExtClassLoader Also failed to load , Will use AppClassLoader To load the , If AppClassLoader Also failed to load , Then an exception will be reported ClassNotFoundException.
Postscript
This article is basically “ stereotyped writing ”, There are not many dry goods , But it is JVM An integral part of the series , Anyway, it just gives me a kind of “ It's a pity to abandon the tasteless food ” The feeling of , How to put it? , Or not? JVM Memory knowledge is interesting 、 The reality of coming , So just for understanding .

边栏推荐
- 【pytorch 記錄】pytorch的變量parameter、buffer。self.register_buffer()、self.register_parameter()
- Mvcc and bufferpool (VI)
- JVM heap (IV)
- Linked list: palindrome linked list
- Typical application of ACL
- Ijkplayer source code - remuxing
- Prometheus node_exporter安装并注册为服务
- CDN single page reference of indexbar index column in vant framework cannot be displayed normally
- Vscode liveserver use_ Liveserver startup debugging
- Exercise 8-3 rotate array right
猜你喜欢

C simple understanding - generics

Available types in C #_ Unavailable type_ C double question mark_ C question mark point_ C null is not equal to

Detailed explanation of handwritten numeral recognition based on support vector machine (Matlab GUI code, providing handwriting pad)

專業的數據庫管理軟件:Valentina Studio Pro for Mac

Few-shot Unsupervised Domain Adaptation with Image-to-Class Sparse Similarity Encoding

C simple understanding - arrays and sets

二叉树初始化代码

Wechat applet coordinate location interface usage (II) map interface

Scala implements workcount

The weight of the input and textarea components of the applet is higher than that of the fixed Z-index
随机推荐
2022.05.29
Open source - campus forum and resource sharing applet
IOS development interview knowledge sorting - OC Foundation (II)
Introduction to facial expression recognition system -- offline environment configuration
Available types in C #_ Unavailable type_ C double question mark_ C question mark point_ C null is not equal to
Ijkplayer source code -- mnatemediaplayer of ijkmediaplayer
C simple understanding - generics
Introduction to Sitemap_ Sitemap online generation and sorting
Collection of IOS development interview and underlying learning videos
Scala implements workcount
SQL execution process in MySQL (3)
C method parameter: in
JMeter quick start
Keil去掉烦人的ST-Link更新提示
Linked list: reverse linked list
开源-校园论坛和资源共享小程序
Entity framework extends the actual combat, small project reconfiguration, no trouble
The extra money we made in those years
Keil removes annoying st link update tips
Wechat applet obtains the current location (startlocationupdate, onlocationchange, offlocationchange)