当前位置:网站首页>Parental delegation mechanism
Parental delegation mechanism
2022-06-29 17:45:00 【xixingzhe2】
1、 Concept
When a class loader receives a class load request , It doesn't load the specified class directly , Instead, delegate the request to your parent loader to load it . Only when the parent loader cannot load this class , The current loader will be responsible for loading the class .
2、 Four types of Loaders
Java The following four types of loaders are provided in , Each loader has a specified load object , As follows
- Bootstrap ClassLoader( Start class loader ) : Mainly responsible for loading Java The core library ,%JRE_HOME%\lib Under the rt.jar、resources.jar、charsets.jar and class etc. .
- Extention ClassLoader( Extend the classloader ): Mainly responsible for loading Directory %JRE_HOME%\lib\ext In the catalog jar Bao He class file .
- Application ClassLoader( Application class loader ) : Mainly responsible for loading the current application classpath All classes under
- User ClassLoader( User defined class loader ) : user ( Programmer ) Custom class loader , Can load the specified path class file .
These four kinds of loaders have the following relationship , When loading classes , Although user-defined classes will not be used by bootstrap classloader or extension classloader load ( Determined by the loading range of the class loader ), But the code implementation will still be delegated until bootstrap classloader, The upper layer cannot load , Then whether the lower layer can load , If you can't load , It will trigger findclass, Throw out classNotFoundException.

Be careful :
The hierarchical relationship between loaders that exists here does not exist in the form of inheritance , But in combination . The following is classLoader Source code .
3、classLoader Source code analysis
open “java.lang” Under bag ClassLoader class , find loadClass Method :
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
// -----??-----
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
// First , Check whether it has been loaded by the class loader
Class<?> c = findLoadedClass(name);
if (c == null) {
try {
// There is a parent loader , Recursive handover to parent loader
if (parent != null) {
c = parent.loadClass(name, false);
} else {
// Up to the top Bootstrap Class loader
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.
c = findClass(name);
}
}
return c;
}The following figure is the flow chart of the above code

It's easier for us to understand from the above picture , When one Hello.class When such a file is to be loaded . Regardless of our custom class loader , First of all, it will be in AppClassLoader Check if it has been loaded in , If so, there is no need to load . without , Then you'll get the parent loader , Then the parent loader is invoked. loadClass Method . Similarly, in the parent class, you will first check whether you have loaded , If you don't go up again . Notice this recursive process , Until arrival Bootstrap classLoader Before , They are all checking whether they have been loaded , You don't choose to load it yourself . until BootstrapClassLoader, There is no parent loader , At this time, I began to consider whether I could load , If you can't load , Will sink to the child loader to load , All the way to the bottom , If no loader can load , Will throw ClassNotFoundException.
4、 The significance of parental delegation mechanism
4.1 By delegation , It can avoid the repeated loading of classes
When the parent loader has loaded a class , The child loader will not reload the class .
4.2 By parental appointment , It also guarantees security ( Sandbox security mechanism )
because Bootstrap ClassLoader When loading , Only... Will be loaded JAVA_HOME Medium jar The class in the bag , Such as java.lang.Integer, This class will not be replaced at will , Unless someone runs to your machine , Destroy your life JDK. that , You can avoid having someone customize a device that has destructive functions java.lang.Integer Be loaded . This can effectively prevent the core Java API Be tampered with . This will ensure that you are right java Protection of core source code , This is the sandbox security mechanism .
4.4 summary

5、 How to customize class loader
ClassLoader The process inside
- loadclass: Parent delegate mechanism , The child loader delegates the parent loader to load , When both parent loaders fail to load , The child loader passes findclass Self loading
- findclass: The current classloader is based on the path and class File name load bytecode , from class Read byte array from file , And then use defineClass
- defineclass: Based on byte array , return Class object
We are ClassLoader Found inside findClass Method , It is found that this method throws an exception directly , It should be left to subclass implementation .
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}Come here , We should understand ,loadClass Method uses the template method pattern , The main logic is parental delegation , But how will class File to Class The object steps , It has been handed over to subclasses to implement .
If we need a custom class loader , Just inherit ClassLoader, And rewrite findClass The method can .
Now there is a simple example ,class The file is still in the file directory :
package com.ybw.jdk8.demo.claz.loader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* Custom class loaders
*
* @author ybw
* @version V1.0
* @className MyClassLoader
* @date 2022/6/28
**/
public class MyClassLoader extends ClassLoader {
/**
* Class loading path , Does not contain a filename
*/
private String path;
public MyClassLoader(String path) {
super();
this.path = path;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] bytes = getBytesFromClass(name);
assert bytes != null;
// Read byte array , Turn into Class object
return defineClass(name, bytes, 0, bytes.length);
}
/**
* Read class file , Convert to byte array
*
* @param name
* @methodName: getBytesFromClass
* @return: byte[]
* @author: ybw
* @date: 2022/6/28
**/
private byte[] getBytesFromClass(String name) {
String absolutePath = path + "/" + name + ".class";
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(new File(absolutePath));
bos = new ByteArrayOutputStream();
byte[] temp = new byte[1024];
int len;
while ((len = fis.read(temp)) != -1) {
bos.write(temp, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != bos) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
MyClassLoader classLoader = new MyClassLoader("C://1");
Class test = classLoader.loadClass("com.ybw.jdk8.demo.dto.StudentDTO");
test.newInstance();
}
}StudentDTO class :
package com.ybw.jdk8.demo.dto;
/**
* @author ybw
* @version V1.0
* @className StudentDTO
* @date 2022/6/28
**/
public class StudentDTO {
public StudentDTO() {
System.out.println("student classloader is " + this.getClass().getClassLoader().toString());
}
}
Generate class Put it in the corresponding directory

function MyClassLoader Of main After the method , You can see the output :

I can see you ,Student.class It was actually loaded by our custom class loader .
6、 Destruction of parental delegation
6.1 With Tomcat Class loading as an example ,Tomcat If you use the default parental delegation class loading mechanism, will it work ?
Tomcat It's a web Containers , So what problem does it have to solve :
- One web Container may need Deploy two applications , Different applications may Depending on different versions of the same third-party class library , You can't require the same class library to have only one copy on the same server , So make sure that each application's class library is independent , Make sure they are isolated from each other .
- Deployed in the same web The same version of the same class library in the container can be shared . otherwise , If the server has 10 Applications , Then there must be 10 Load the same class library into the virtual machine .
- web Containers also have their own dependent class libraries , Can't be confused with an application's class library . Based on safety considerations , The class library of the container should be isolated from the class library of the program .
- web The container should support jsp Modification of , We know ,jsp The file is also compiled into class Files to run in a virtual machine , But the program is modified after running jsp It's a common thing , web The container needs to support jsp No need to restart after modification .
Tomcat If you use the default parental delegation class loading mechanism, will it work ?
The answer is No . Why? ?
The first question is , If you use the default classloader mechanism , So it's impossible to load different versions of two same class libraries , The default class adder is no matter what version you are , Only care about your fully qualified class name , And only one .
The second question is , The default classloader can be implemented , Because his job is to ensure uniqueness .
The third question is the same as the first one .
Look at the fourth question , How to do that jsp Hot loading of files ,jsp The document is actually class file , So if it changes , But the class name is the same , Class loader will directly take the existing in method area , The modified jsp It won't reload . So what to do ? It can be unloaded directly jsp Class loader for files , So you should think of , Every jsp The file corresponds to a unique classloader , When one jsp The file has been modified , Just uninstall this jsp Class loader . Recreate class loader , Reload jsp file .
6.2 Tomcat Custom loader details
The loading range of each loader is :
- Common ClassLoader: Main load common Directory of resources . Load... In the path class Can be Tomcat The container itself and the individual webapp visit .
- Catalina ClassLoader: Main load server Directory of resources .Tomcat Container private classloader , Load... In the path class Not for webapp so .
- Shared ClassLoader: Main load shared Directory of resources . each webapp Shared classloader , Load... In the path class Can be used by all webapp visit , But for Tomcat The container is not visible
- Webapp ClassLoader: Each application will correspond to an instance of this type , It mainly loads... Under this application WEB-INF Resources under . each Webapp Private classloader , Load... In the path class Only for the present Webapp so , Such as loading war Related classes in the package , Every war Package applications have their own WebappClassLoader, Achieve mutual isolation , Like different war Package applications introduce different spring edition , So that the implementations can load their own spring edition .
- JasperLoader: every last jsp The file will correspond to an instance of this type , Just to modify jsp It works in time .
As you can see from the delegation relationship in the figure :
CommonClassLoader All classes that can be loaded can be Catalina ClassLoader and SharedClassLoader Use , Thus, the sharing of public class libraries is realized , and CatalinaClassLoader and Shared ClassLoader Classes that you can load are isolated from each other .
WebAppClassLoader have access to SharedClassLoader Class loaded , But each WebAppClassLoader Instances are isolated from each other .
and JasperLoader The loading range of is just this JSP The one compiled by the file .Class file , It appears for the purpose of being discarded : When Web The container detected JSP When the document is modified , Will replace the current JasperLoader Example , And by building a new Jsp Class loader to achieve JSP Of documents HotSwap function .
6.3 tomcat Contrary to java Is the recommended parent delegation model available ?
The answer is : Contrary to .
The parental delegation model requires that in addition to the top-level boot loader , The rest of the class loaders should be loaded by their own parent class loaders .
Obviously ,tomcat Not so ,tomcat To achieve isolation , Didn't abide by the agreement , Every webappClassLoader Load... In your own directory class file , Will not be passed to the parent loader .
Be careful :
- For some classes in the standard class library , such as Object class , Will cause the system class loader to load , Then delegate until the class loader starts , This process does not violate parental delegation .
- about webapp Class unique to , It is webappClassLoader Load by yourself , Failed to load before the parent loader loads , Obviously against parental delegation .
- The same JVM Inside , Two class objects with the same package name and class name can coexist , Because their classloaders can be different , So see if the two class objects are the same , In addition to seeing whether the package name and class name of the class are the same , They also need to have the same class loader to think they are the same .
Reference article :
边栏推荐
- 迈动互联中标大家保险集团
- Uploading files using AutoIT
- Error:Connection refused: connect
- mysql如何查询表的字符集编码
- Yurun multidimensional makes efforts in the charity field and bravely resists the corporate public welfare banner
- Maidong Internet won the bid of Dajia Insurance Group
- 使用autoIt 上传文件
- Basic operations such as MySQL startup under Windows platform
- Browser large screen capture
- SRM系统是什么系统?如何应用SRM系统?
猜你喜欢

Matlab farthest point sampling (FPS)

底层内功修养
![[webdriver] upload files using AutoIT](/img/69/8c27626d515976b47f1df4831d09c8.png)
[webdriver] upload files using AutoIT

mysql. What is the concept of sock

OpenFeign使用步骤 轮询策略与权重 log4j使用 openFeign拦截器的配置

关于日期相加减问题

VB.Net读写NFC Ntag标签源码
![Fill in the next right node pointer of each node [make good use of each point - > reduce the space-time complexity as much as possible]](/img/33/bda0a898bfe3503197026d1f62e851.png)
Fill in the next right node pointer of each node [make good use of each point - > reduce the space-time complexity as much as possible]

双亲委派机制

与爱同行,育润走进贫困家庭,助推公益事业
随机推荐
R language uses user-defined functions to write deep learning linear activation functions and visualize linear activation functions
MATLAB 最远点采样(FPS)
R语言使用自定义函数编写深度学习线性激活函数、并可视化线性激活函数
VB. Net read / write NFC ntag tag source code
基于STM32F103ZET6库函数PWM输出实验
Bags of Binary Words for Fast Place Recognition in Image Sequenc
一次采集JSON解析错误的修复
R language ggplot2 visualization: use the patchwork package (directly use the plus sign +) to horizontally combine a ggplot2 visualization result and a plot function visualization result to form the f
位图的详细介绍及模拟实现
The soft youth under the blessing of devcloud makes education "smart" in the cloud
mac安装php7.2
软件快速交付真的需要以安全为代价吗?
如何使用B/S开发工具DevExtreme的图表控件 - 自定义轴位置?
R语言将距离矩阵输入给hclust函数进行层次聚类分析,method参数指定两个组合数据点间的距离计算方式、plot函数可视化层次聚类的树状图(dendrogram)
R语言dplyr包filter函数通过组合逻辑(与逻辑)过滤dataframe数据中的数据、其中一个字段的内容等于指定向量中的其中一个,并且另外一个字段值大于某一阈值
国外LEAD赚钱,做个网站真的很简单
R language ggplot2 visualization: use the patchwork package (directly use the plus sign +) to horizontally combine the two ggplot2 visualization results, and then horizontally combine them with the th
selenium上传文件
VB.Net读写NFC Ntag标签源码
与爱同行,育润走进贫困家庭,助推公益事业
