当前位置:网站首页>JVM class loading mechanism
JVM class loading mechanism
2022-07-02 05:19:00 【Share and summary】
List of articles
summary
Class After the file is loaded by the class loader , stay JVM A description will be formed Class Meta information object of structure , Through the meta information object, you can know Class Structure information of : Such as constructor , Properties and methods, etc ,Java Allow users to borrow this Class The related meta information object is called indirectly Class The function of the object .
The virtual machine takes the data describing the class from class File loaded into memory , And verify the data , Transform resolution and initialization , Finally, it can be directly used by virtual machine Java type , This is the class loading mechanism of virtual machine .
What is class loading ?
Class loading refers to the loading of classes .class Binary data in the file is read into memory , Place it in the method area of the runtime data area , Then create a... In the heap area java.lang.Class object , Used to encapsulate the data structure of the class in the method area . The final product of class loading is in the heap area Class object ,Class Object encapsulates the data structure of class in method area , And to the Java The programmer provides an interface to access the data structure in the method area .
Class loader does not need to wait until a class is “ First active use of ” And then load it ,JVM The specification allows a class loader to preload a class when it is expected to be used , If you encounter .class Missing or wrong file , The class loader must report an error the first time the program actively uses the class (LinkageError error ) If this class has not been actively used by the program , Then the classloader will not report errors .
1. Class loader
Class loaders are divided from top to bottom :
1.Bootstrap ClassLoader Start class ( Boot class ) loader : By default, it will load JAVA_HOME/lib In the catalog jar. Use C/C++ The realization of language , Nested in JVM Inside . It's used to load Java The core of the library (String class ……)(JAVA_HOME/jre/lib/rt.jar、resource.jar or sun.boot.class.path The content of the path ), Including loading extension class loader and Application Loader . No parent loader . For safety reasons ,Bootstrap The boot class loader only loads packages named java、javax、sun Class with equal beginning .
2.Extention ClassLoader Extend the classloader : Load by default JAVA_HOME/lib/ext In the catalog jar.Java Language writing , from sun.misc.LauncherExtClassLoader Realization . Derive from ClassLoader class . from java.ext.dirs Load the class library in the directory specified by the system property , Or from JAVA_HOME/jre/lib/ext subdirectories ( Extended Directory ) Download the class library . If the user created JAR Put it in this directory , It will also be automatically loaded by the extension class loader .
3.Application ClassLoader System class ( Application class ) loader : Like our web application , Will load web In the program ClassPath Next class .java Language writing , from sun.misc.Launcher$AppClassLoader Realization . It's responsible for loading environment variables classpath Or system properties java.class.path Specify the class library under the path For user-defined classes : The system class loader is used for loading by default adopt ClassLoader.getSystemClassLoader() Method to get the class loader
4.User ClassLoader User defined class loader : Defined by the user
Only those loaded by the same classloader instance with the same file name class The file is considered the same class
perform java The program , Will start a JVM process ,JVM During startup, some initialization operations will be done , For example, get system parameters and so on , Then create a startup class loader , Used for loading JVM Some classes that must be in memory at runtime , At the same time, two other class loaders will be created, the extension class loader and the system class loader .
2. Class loading process

The first is the loading process (Loading), It is Java Read bytecode data from different data sources to JVM in , And map it to JVM Approved data structures (Class object ), The data sources here may be in various forms , such as jar file ,class file , Even network data sources ; If the input data is not ClassFile Structure , It will be thrown out. ClassFormatError. The loading phase is the user involvement phase , We can customize the classloader , To implement your own class loading process .
The second stage is to connect (Linking), This is the core step , Simply put, the original class definition information is smoothly transferred to JVM In the process of operation . This can be further subdivided into three steps :
1, verification (Verification), This is an important guarantee for the security of virtual machines ,JVM Need to verify that byte information is consistent with Java Virtual machine specification , Otherwise it's considered to be VerifyError, This prevents malicious information or non-conforming information from harming JVM Operation of , The validation phase has the potential to trigger more class Loading .
2, Get ready (Pereparation), Create static variables in a class or interface , And initialize the initial value of the static variable . But here it is. “ initialization ” It is different from the following display initialization phase , The emphasis is on allocating the required memory space , It's not going to go any further JVM Instructions .
3, analysis (Resolution), In this step, the symbols in the constant pool are referred to (symbolic reference) Replace with direct reference . stay Java In the virtual machine specification , It introduces the class in detail , Interface , Methods and fields, etc .
Finally, the initialization phase (initialization), This step actually performs the code logic of class initialization , Include static field assignment actions , And execute the logic in the static initialization block in the class definition , The compiler will sort out this part of the logic in the compilation phase , The initialization logic of the parent type takes precedence over the logic of the current type . Let's talk about the parental delegation model , Simply put, when the loader (Class-Loader) When trying to load a type , Unless the parent loader cannot find the corresponding type , Otherwise, try to delegate this task to the parent loader of the current loader . The purpose of using the delegation model is to avoid repeated loading Java type .
The so-called class loading process is to put our java The original document passed javac The bytecode file generated after compilation is loaded into jvm Memory , Give Way jvm The process of executing bytecode instructions .
3. Parent delegate mechanism
Java The loading mechanism is a parental delegation mechanism to load classes , Why use this way ? This is to make sure that 【 If the loaded class is a system class , Then priority will be given to Bootstrap ClassLoader 、Extension ClassLoader Load first , Instead of using our custom ClassLoader To load the , Ensure the safety of the system !】
Is the current class loader ( Take the system class loader as an example ) When loading a class , Entrusted to his parents ( Note that the parent here refers to the parent in the class loader parent Property points to the class loader ) Load first . The parent class loader also delegates to its parents when loading , So again and again , Until a classloader has no parents ( Usually refers to the parents as null, That is, the current parent is the extended class loader , Its parent To start the class loader ), Then start looking for... Under their respective class paths in turn 、 load class class .
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 exists, the parent loader , Then further entrust , Recursion in turn , The boot class loader that finally reaches the top level ; If the parent loader can complete the class loading task , You're back , If the parent class cannot finish loading , The subclass loader will load , This is the parent delegation model .
advantage :
1. It can avoid the repeated loading of classes
2. Prevent the core API Be tampered with
summary
jvm The process of loading classes in includes : load , link ( verification , analysis , Get ready ), Initialize these five stages .
1. load : Is the first phase of class loading , He has three things to accomplish :
1 Get the binary byte stream of a class by its fully qualified name
2. Convert the static storage structure represented by this byte stream into the runtime structure of the method area .
3. This class exists in memory Class object , As the data access entry of this class in the method area
2. verification : The first step of link during verification , The purpose of this stage is to ensure Class The byte stream of the file contains information consistent with java Virtual machine specification , Ensure that this information will not endanger the security of the virtual machine itself . These include : File format inspection , Metadata validation , Bytecode check , Symbol reference check .cafe baby Magic
3. Get ready : This stage is formally defined for variables in the class ( Static variables By static Decorated variable ) Allocate memory and set initial values of class variables .public static int a = 1; Then in the preparation stage, he will a The assignment is 0 instead of 1;
4. analysis : At this stage java The process of virtual machine replacing symbolic reference in constant pool with direct reference .
5. Initialization phase : This is the last stage of the class loading process , The initialization phase is to execute the class constructor clinit The process of the method, for example, just now a This class variable will be copied as 1.
边栏推荐
- el form 表单validate成功后没有执行逻辑
- Fabric.js IText 上标和下标
- Gee: explore the change of water area in the North Canal basin over the past 30 years [year by year]
- Fabric. JS centered element
- Detailed explanation of Pointer use
- Fabric.js 激活输入框
- Case sharing | intelligent Western Airport
- [opencv] image binarization
- el-cascader回显只选中不显示的问题
- Fabric. JS 3 APIs to set canvas width and height
猜你喜欢
![Gee series: Unit 5 remote sensing image preprocessing [GEE grid preprocessing]](/img/1e/cf0aa09c2fce2278386f12eae4a6cd.jpg)
Gee series: Unit 5 remote sensing image preprocessing [GEE grid preprocessing]

Using Kube bench and Kube hunter to evaluate the risk of kubernetes cluster

Fabric. JS upload local image to canvas background

Nodejs (03) -- custom module

LeetCode 241. 为运算表达式设计优先级(分治/记忆化递归/动态规划)

【pyinstaller】_get_sysconfigdata_name() missing 1 required positional argument: ‘check_exists‘

Storage of data

Using QA band and bit mask in Google Earth engine
![Gee series: unit 7 remote sensing image classification using GEE [random forest classification]](/img/01/ba9441b7b1efaed85c464316740edb.jpg)
Gee series: unit 7 remote sensing image classification using GEE [random forest classification]

黑马笔记---Set系列集合
随机推荐
Fabric.js 将本地图像上传到画布背景
Fabric.js 背景不受视口变换影响
Feign realizes file uploading and downloading
延时队列两种实现方式
黑马笔记---Map集合体系
Ubuntu 20.04 installing mysql8
ERP management system development and design existing source code
leetcode存在重复元素go实现
How to make an RPM file
Collectors.groupingBy 排序
Fabric.js 3个api设置画布宽高
Nodejs (02) - built in module
Operator details
Draw a wave chart_ Digital IC
7.1 Résumé du concours de simulation
Ansible installation and use
Fabric.js IText 手动设置斜体
Dark horse notes -- Set Series Collection
National all Chinese Automatic Test Software apifox
线程池批量处理数据