当前位置:网站首页>1. JVM class loading mechanism
1. JVM class loading mechanism
2022-07-16 09:13:00 【huisheng_ qaq】
Analysis of class loading principle
One , Operation principle
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-8xkg5vSM-1654916732266)(C:\Users\HULOUBO\AppData\Roaming\Typora\typora-user-images\1654862329459.png)]](/img/18/4325173f00eec1688c0e59075bd57b.png)
1, use c The language program starts a java virtual machine , Create boot class loader (c Realization )
2,c Language back call java Code to create JVM The starter
3, adopt Launcher class , As a boot class , To load various class loaders
4, Load the class through a series of processes of class loading
Two , Class loading process
2.1 load -> verification -> Get ready -> analysis -> initialization

load : Load bytecode file from disk into memory
verification : Check whether the contents comply with java Specification of virtual machine
Get ready : Assign some static variables to the initial value of a default value
analysis : Convert symbolic references to direct references , Some static methods will be transformed into an address in memory , That is to say, it was just a class or a method , Later, you can find the specific location in the memory .
initialization : Some static variables will be initialized to the final value , Such as executing static code blocks
jvm It uses lazy loading to load these class, That is to say, only when this class is used can it be loaded
You can view a case
package zalei;
/** * @Author: zhenghuisheng * @Date: 2022/6/11 11:20 */
public class TestLoad {
static {
System.out.println("*************load TestDynamicLoad************");
}
public static void main(String[] args) {
new A();
System.out.println("*************load test************");
B b = null; //B Will not load , Unless it's done here new B()
//B b2 = new B();
}
}
class A {
static {
System.out.println("*************load A************");
}
public A() {
System.out.println("*************initial A************");
}
}
class B {
static {
System.out.println("*************load B************");
}
public B() {
System.out.println("*************initial B************");
}
}
give the result as follows , If new 了 B Words , It will be right B Loading , Load static blocks first -
*************load TestDynamicLoad************
*************load A************
*************initial A************
*************load test************
2.2 Class loader and parental delegation model
1, loader
1, Boot class loader : load jre Below lib The core class library under the directory
2, Extend the classloader : load jre Below lib Extension under directory jar package 、
3, Application class loader : Mainly responsible for loading ClassPath Package under path , Load the customized classes
4, Custom class loaders : Responsible for loading the class package under the user-defined path
2,Launcher
//Launcher Construction method of
public Launcher() {
Launcher.ExtClassLoader var1;
try {
// Construct extension class loader , During construction, set its parent loader to null
var1 = Launcher.ExtClassLoader.getExtClassLoader();
} catch (IOException var10) {
throw new InternalError("Could not create extension class loader", var10);
}
try {
// Construct application class loader , During construction, set its parent loader to ExtClassLoader,
//Launcher Of loader The property value is AppClassLoader, We usually use this class loader to load our own applications
this.loader = Launcher.AppClassLoader.getAppClassLoader(var1);
} catch (IOException var9) {
throw new InternalError("Could not create application class loader", var9);
}
Thread.currentThread().setContextClassLoader(this.loader);
String var2 = System.getProperty("java.security.manager");
}-
1, adopt c The language initializes a Luancher class , Will build a loader of boot classes (bootStrapClassLoader)
2, Like the code above ,Luancher Two class loading constructors are constructed in the constructor , They are the loaders of extension classes ExtClassLoader And application class loader AppClassLoader
3, First load the extension class loader , After loading , Then load the application class loader , Generally, we load our own programs through the application class loader
All class loaders in this are inherited ClassLoader
2.3 Parent delegate mechanism
1, Schematic diagram

Custom loader —> Application class loader —> Extend the classloader —> Boot class loader
If the parent class does not load successfully , Then load it again from top to bottom
1, First, load through the application class loader , Judge whether the class has been loaded in the class collection loaded by the Application Loader
2, If the application loader has not been loaded , The class will be loaded through the extended class loader , Judge from the class collection
3, If the extension class is still not loaded , Will go to his father loader bootStrap Boot class loader , See whether the class collection is loaded
4, If the boot class loader ( Root loader ) Still failed to find , Then return the class loader of the current class in turn , Load again
Mainly when loading a class , The parent loader will be used first to load this class , If you can't find it, you will continue to find the upper level , If all parent loaders cannot find the target class in their own load class path , Find and load the target class in your own class loading path . It means : First load it with my father , No, it's up to my son to load it
2, Source analysis
// Check whether the current class loader has loaded the class
Class<?> c = findLoadedClass(name);
if (c == null) {
long t0 = System.nanoTime();
try {
if (parent != null) {
// If the parent loader of the current loader is not empty, delegate the parent loader to load the class
c = parent.loadClass(name, false);
} else {
// If the current loader parent loader is empty, delegate the boot class loader to load the class
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
// Will be called URLClassLoader Of findClass Method to find and load the class in the classpath of the loader
c = findClass(name);
You can also know through the source code :
1, First , Check to see if the class with the specified name has been loaded , If it's loaded , There's no need to load , Go straight back to .
2, If this class has not been loaded , that , Let's see if there's a parent loader ; If there is a parent loader , Is loaded by the parent loader ( That is to call parent.loadClass(name, false);). Call or call bootstrap Class loader to load .
3, If the parent loader and bootstrap None of the class loaders found the specified class , So the method of calling the current class loader findClass Method to complete class loading .ClassLoader Of loadClass Method , It implements the mechanism of parents' appointment
3, The design benefits of parental delegation mechanism
1, Sandbox security mechanism : His writing java.lang.String.class Class will not be loaded , This prevents the core API The library was tampered with at will
2, Avoid duplicate loading of classes : When the father has loaded the class , There is no need ClassLoader Load again , Ensure the uniqueness of the loaded class
2.4 Custom class loaders
Need to inherit ClassLoader class , And rewrite the inside findClass() Method . You can create a class in the local disk , How to load directly through the local disk when loading , You don't need to use those class loaders to load , This completes the loader of custom classes
package zalei;
import java.io.FileInputStream;
import java.lang.reflect.Method;
/** * @Author: zhenghuisheng * @Date: 2022/6/10 23:09 */
public class MyClassLoaderTest {
static class MyClassLoader extends ClassLoader {
private String classPath;
public MyClassLoader(String classPath) {
this.classPath = classPath;
}
private byte[] loadByte(String name) throws Exception {
name = name.replaceAll("\\.", "/");
FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
int len = fis.available();
byte[] data = new byte[len];
fis.read(data);
fis.close();
return data;
}
protected Class<?> findClass(String name) throws ClassNotFoundException {
try {
byte[] data = loadByte(name);
//defineClass Convert a byte array to Class object , This byte array is class The final byte array after the file is read .
return defineClass(name, data, 0, data.length);
} catch (Exception e) {
e.printStackTrace();
throw new ClassNotFoundException();
}
}
}
/** * The following disk paths need to be created manually * @param args * @throws Exception */
public static void main(String args[]) throws Exception {
// Initialize custom class loader , Initializes the parent class first ClassLoader, It sets the parent loader of the custom class loader as the application class loader AppClassLoader
MyClassLoader classLoader = new MyClassLoader("D:/test");
//D Disk creation test/com/zhenghuisheng/jvm What level of directory , take User Class replication class User.class Drop in the directory
// You need to create a User Class in this path
Class clazz = classLoader.loadClass("com.zhenghuisheng.jvm.User");
Object obj = clazz.newInstance();
Method method = clazz.getDeclaredMethod("sout", null);
method.invoke(obj, null);
System.out.println(clazz.getClassLoader().getClass().getName());
}
}
2.5 Break the parental delegation machine
There is this class in the application , There is also this custom class in the disk , Load directly through the disk at one time , There is no need to use the parent class loader , This breaks the parental delegation mechanism . Mainly through rewriting findClass() Method , Modify the logic of the parent delegation mechanism . Let this findClass Directly find the path in the disk , Instead of writing those layers, you can find the parent loader to load .
边栏推荐
猜你喜欢

音视频学习(六)——PCM音频基础

Details of assets of odoo

Detailed explanation of odoo form view (I)

Anonymous pipeline principle and detailed explanation (very practical)

ODOO form视图详解(一)

容错、熔断的使用与扩展

Three methods are used to simulate the implementation of the library function strlen to deepen the understanding of strlen

《A Unified Generative Framework for Aspect-Based Sentiment Analysis》论文阅读

odoo action分析(action.client,action.act_window,action.server)

云上解锁Web3.0 阿里云XR平台助力彼真科技呈现沉浸式演唱会
随机推荐
C language register skills (struct and union)
The use of lambda function in odoo
PHP gets the names of all sub files in the directory (including cases, screenshots, and codes)
内存映射原理及详解(非常实用)
敏捷实践:开站会只问昨天做了什么?今天准备做什么就行了吗?
哪种敏捷实践能让“老板”最快看到团队敏捷转型的效果?
X书关键词搜索
How to set various displays in 3dmax2021?
Qt+vs project imports relevant DLLs under the release/debug folder (very practical)
php获取目录下的全部子文件名称(含案例、截图、代码)
jmm内存模型及volatile实现原理
Detailed explanation of odoo form view (I)
Transformer 落地出现 | Next-ViT实现工业TensorRT实时落地,超越ResNet、CSWin
3,jvm垃圾回收器
babylon. JS height map
排序——基数排序
arduino上传程序出错不成功常见的问题解决
3dmax2021 中的各种显示相关如何设置?
三种方法模拟实现库函数strlen,加深对strlen的理解
天田AMADA数控折弯机触摸屏维修RGM21003主机电路板维修