当前位置:网站首页>JVM class loader
JVM class loader
2022-04-23 02:33:00 【Flying Holland】
One 、JVM Memory structure
1. Schematic diagram
2. Detail
Two 、 Class loader Introduction
1. Basic introduction
- Classloader subsystem : Only responsible for loading from the file system or network Class file ,class The file has a specific file ID at the beginning
1. ClassLoader Only responsible for class Loading of files , As for whether it can run , hand Execution Engine decision
2. Class information loaded , Stored in a memory space called the method area
2.1 Class information
2.2 Store information about runtime constants ( Literal strings and numeric constants )
2. role
1. class file On the local hard drive , It can be understood as the template drawn by the designer on paper
Finally, when the template is executed , Will be loaded into JVM in , According to the template , To create a n An identical example
2. class file Load into... By binary stream jvm in , go by the name of DNA Metadata template , Put it in the method area
3. .class--jvm-- Metadata templates : Class loader is the role of a courier
3、 ... and 、 Class loading
1. Loading
1.1 Source of documents
- Load directly from the local file system
- Get... Through the Internet
- from zip Read in compressed package , Later it was converted to jar,war Format
- Runtime compute generation : A dynamic proxy
- Generated from other files :jsp
- Get... From the encrypted file , prevent Class The file is protected by decompilation , Decryption is required when reading
1.2 Loading The process
1. Through the fully qualified class name of a class , Gets the binary byte stream that defines the class
2. Convert the static storage structure represented by the byte stream to the runtime data structure of the method area ( Metadata )
3. In heap memory , Generate a that represents the class java.lang.Class object , As the access to all kinds of data of this class in method area
package com.nike.erick.d04;
import java.lang.reflect.Field;
public class ErickService {
public String name;
public String address;
public String getName() {
return "erick";
}
public static void main(String[] args) {
Class<ErickService> serviceClass = ErickService.class;
Field[] fields = serviceClass.getFields();
for (Field field : fields) {
System.out.println(field.getName());
}
}
}
2. Linking
2.1 Verify
- Make sure class The byte stream of the file contains information that meets the requirements of the current virtual machine , Ensure the correctness of the loaded class , Does not harm the security of virtual machine itself
- File format verification , Metadata validation , Bytecode verification , Symbol reference validation
1. CA FE BA BE: adopt 《 Binary viewer 》, Find all .class Files start with this ( magic number )
2.2 Prepare
- Allocate memory for a class variable and set the default initial value of the class variable , That's zero
- It doesn't contain final Embellished static, because final It will be allocated at compile time , In the preparation phase, the initialization will be displayed
- Initialization will not be assigned to instance variables , Class variables are assigned in the method area , Instance variables are assigned to... Along with the object Java In the pile
2.3 Resolve
- For example, a .class file , In preparation , You need to do some initialization preparations for its parent class
3. Initialization
3.1 class constructor <clinit> Method
1. The initialization phase is : Execute class constructor methods <clinit>() The process of
a. This method does not need to define , yes javac The compiler automatically collects information from classes , And merge
Class variables (static) Assignment action of Statements in static code blocks
b. Execution order : From the source file from top to bottom
c. If the above two data are not included , Then there will be no clint()
# Because the collection order
d. If the class has a parent class , JVM Ensure that subclasses <clinit() Before implementation , Of the parent class <clinit> Go ahead and execute
# because <clint> Is used to load class variables , So you only need to load once , And cache in meta space ( Method area )
# Class loading natural thread safety
e. Virtual machines guarantee , A class of <clinit>() Method is locked synchronously under multithreading
stay IDEA Midrange jclasslib Check it out.
- contain <clinit> Method
- It doesn't contain <clinit> Method
- Child parent <clinit> Method loading order
- Synchronous locking under multithreading
package com.nike.erick.d05;
public class MultiThread {
public static void main(String[] args) {
new Thread(() -> {
Erick erick = new Erick();
}).start();
new Thread(() -> {
Erick erick = new Erick();
}).start();
}
}
class Erick {
static {
if (true) {
System.out.println(" Start initializing this class ");
while(true){
}
}
}
}
3.2 Constructor of class
1. <clinit>() and Constructor of class It's not the same thing
2. The constructor is from the perspective of virtual machine <init> Method
- Parameterless constructors
- With a reference constructor
Four 、 Classloader classification
- according to JVM Specification definition
1. Boot class loader (Bootstrap ClassLoader)
- Only responsible for loading the core class library of the system , For providing JVM Its own class ( Such as String class )
- Use c,c++ To achieve , No inheritance ClassLoader, No parent loader
- Nested in JVM Inside
- Responsible for loading platform class loader and system class loader ( Because they are also targets ), Also specify as their parent class loader
- For safety reasons , Only the package name is loaded java javax sun Initial class
- One JVM There will only be one , Print as null
2. Custom class loaders (User-Defined ClassLoader)
- Derived from abstract classes ClassLoader Class loader for
- It's not that programmers customize class loaders
- Use java The realization of language
- The parent loader is BootstrapClassLoader( Parent means : You are loaded by me , adopt getParent)
2.1 PlatformClassLoader( Platform class loader )
- jdk.internal.loader.ClassLoaders$PlatformClassLoader To achieve
- from java Load in the specified directory jar package ( It's not a core library , If user files are placed in this directory , Will also be loaded by this class )
2.2 AppClassLoader( System class loader )
- jdk.internal.loader.ClassLoaders$AppClassLoader Realization
- Responsible for loading environment variables classpath Or system properties
- The default class loader in the program ( That is, the class written by the user )
- adopt ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader() Get class loader
2.3 User defined class loader
- java In daily development , Class loading is almost always performed through the cooperation of the above three kinds of loaders
- When necessary , We can also customize the classloader
1. Isolation loading class
2. Extended load source : For example, read a class from disk .class
3. Modify how classes are loaded
4. Prevent source code leakage : For example, it is encrypted when compiling , Then you need to decrypt when loading
## 1. Custom processes
1. Inherited abstract class java.class.lang.ClassLoader Kind of the way
2. findClass(): Specific logic
If there are no complex requirements , Direct inheritance URLClassLoader that will do
package com.nike.erick.d05;
public class MultiThread {
/* from SystemClassLoader => PlatformClassLoader => BootStrapClassLoader*/
public static void main(String[] args) {
/* Boot class Class loader : Bootstrap class loader*/
ClassLoader stringClassLoader = String.class.getClassLoader();
System.out.println(stringClassLoader);
/* System class loader : AppClassLoader*/
/*jdk.internal.loader.ClassLoaders$AppClassLoader@2c13da15*/
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);
/* Platform class loader :PlatformClassLoader*/
/*jdk.internal.loader.ClassLoaders$PlatformClassLoader@5a39699c*/
ClassLoader platformClassLoader = systemClassLoader.getParent();
System.out.println(platformClassLoader);
/*null*/
ClassLoader bootstrapClassLoader = platformClassLoader.getParent();
System.out.println(bootstrapClassLoader);
/* User defined classes Class loader for 1. jdk.internal.loader.ClassLoaders$AppClassLoader@2c13da15 2. Class loader of system class , One JVM There will only be one */
ClassLoader erickClassLoader = MultiThread.class.getClassLoader();
System.out.println(erickClassLoader);
}
}
5、 ... and 、 Parent delegate mechanism
1. Case list
2. principle
- JVM Yes Class Document adoption Load on demand , Lazy loading
- The parent delegation mechanism is used when loading , That is, to give the request to the parent class for processing
2.1 Can't load
3. advantage
- Avoid classes being repeatedly loaded
- Protect program security , Prevention core API Be tampered with at will
版权声明
本文为[Flying Holland]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230228465580.html
边栏推荐
- RT_Thread自问自答
- SQL server2019 cannot download the required files, which may indicate that the version of the installer is no longer supported. What should I do
- 【ValueError: math domain error】
- 006_redis_jedis快速入门
- Flink real-time data warehouse project - Design and implementation of DWS layer
- SQL server2019无法下载所需文件,这可能表示安装程序的版本不再受支持,怎么办了
- 013_ Analysis of SMS verification code login process based on session
- Day18 -- stack queue
- [XJTU计算机网络安全与管理]第二讲 密码技术
- Go language ⌈ mutex and state coordination ⌋
猜你喜欢
JVM运行时数据区(一)
R language advanced | generalized vector and attribute analysis
【2019-CVPR-3D人体姿态估计】Fast and Robust Multi-Person 3D Pose Estimation from Multiple Views
007_Redis_Jedis连接池
想体验HomeKit智能家居?不如来看看这款智能生态
The importance of ERP integration to the improvement of the company's system
PTA: Romantic reflection [binary tree reconstruction] [depth first traversal]
013_ Analysis of SMS verification code login process based on session
Parental delegation model [understanding]
C语言中*与&的用法与区别 以及关键字static和volatile 的含义
随机推荐
每日一题冲刺大厂第十六天 NOIP普及组 三国游戏
想用Mac学习sql,主要给自己个充足理由买Mac听听意见
007_ Redis_ Jedis connection pool
JDBC JDBC
Arduino esp8266 network upgrade OTA
类初始化和实例初始化面试题
RT_ Thread ask and answer
JSP page nesting
Niuke hand speed monthly race 48 C (I can't understand the difference. It belongs to yes)
[nk]牛客月赛48 D
IAR embedded development stm32f103c8t6 Lighting LED
【2019-CVPR-3D人体姿态估计】Fast and Robust Multi-Person 3D Pose Estimation from Multiple Views
MySQL JDBC programming
Target narak
Yes, from today on, our fans can participate in Netease data analysis training camp for free!
MySQL JDBC编程
Lane cross domain problem
认识进程(多线程_初阶)
001_redis设置存活时间
一个国产图像分割项目重磅开源!