当前位置:网站首页>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
边栏推荐
- [nk]牛客月赛48 D
- 002_Redis_String类型常见的操作命令
- Consider defining a bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs‘
- Tp6 Alibaba Cloud SMS Window message Curl Error 60: SSL Certificate Problem: Unable to get local issuer Certificate
- 007_Redis_Jedis连接池
- 007_ Redis_ Jedis connection pool
- How to recognize products from the perspective of Dialectics
- Web learning record (medium)
- hyperscan --- 1
- The 16th day of sprint to the big factory, noip popularization Group Three Kingdoms game
猜你喜欢

Fast and robust multi person 3D pose estimation from multiple views

006_redis_SortedSet类型

006_ redis_ Sortedset type

Global, exclusive, local Routing Guard
![[XJTU computer network security and management] Lecture 2 password technology](/img/b0/263e8dcbfeb2ce9f504a9c8eb76b07.png)
[XJTU computer network security and management] Lecture 2 password technology

Halo open source project learning (I): project launch

005_ redis_ Set set

定了,今日起,本号粉丝可免费参与网易数据分析培训营!

高效音乐格式转换工具Music Converter Pro

小程序 canvas 画布半圆环
随机推荐
Fast and robust multi person 3D pose estimation from multiple views
Understanding process (multithreading primary)
基于Torchserve部署SBERT模型<语义相似度任务>
010_StringRedisTemplate
On LAN
一、序列模型-sequence model
Solve the problem that the registered Google email Gmail mobile number cannot be used for verification
012_ Access denied for user ‘root‘@‘localhost‘ (using password: YES)
手写内存池以及原理代码分析【C语言】
hyperscan --- 1
[nk]牛客月赛48 D
006_ redis_ Sortedset type
RT_Thread自问自答
从开源爱好者到 Apache 董事,一共分几步?
arduino esp8266 网络升级 OTA
SO库依赖问题
RT_ Thread ask and answer
小程序 读取文件
009_Redis_RedisTemplate入门
[XJTU computer network security and management] Lecture 2 password technology