双亲委派模型与打破双亲委派"/>
3.双亲委派模型与打破双亲委派
目录
- 概述
- 双亲委派
- 什么是双亲委派
- 为什么需要双亲委派
- 双亲委派如何实现
- 为什么需要破坏双亲委派
- 深入DriverManager如何破坏双亲委派
- 如何破坏双亲委派
- 结束
概述
双亲委派
什么是双亲委派
- 当一个类加载器收到类加载任务,会先交给其父类加载器去完成。 因此,最终加载任务都会传递至顶层的启动类加载器,只有当父类加载器无法完成加载任务时,子类才会尝试执行加载任务。
为什么叫双亲,不叫父亲?
The Java platform uses a delegation model for loading classes. The basic idea is that every class loader has a “parent” class loader. When loading a class, a class loader first “delegates” the search for the class to its parent class loader before attempting to find the class itself.
因为是最早的翻译者,导致双亲委派流行起来了。.html
为什么需要双亲委派
主要考虑案例因素,双亲委派可以避免重复加载核心的类,当父类加载器已经加载了该类时,子类加载器不会再去加载。
比如:要加载位于 rt.jar 包中的类 java.lang.Object,不管是哪个加载器加载,最终都委托给顶层的启动类加载器进行加载,就样就可以保证使用不同的类加载器,最终得到的都是同样的 Object 对象。
双亲委派如何实现
ClassLoader 抽像类中的 loadClass 方法
源码如下:
protected Class<?> loadClass(String name, boolean resolve)throws ClassNotFoundException
{synchronized (getClassLoadingLock(name)) {// 第一步,检查此类是否被加载过// First, check if the class has already been loadedClass<?> c = findLoadedClass(name);if (c == null) {// 没有加载过long t0 = System.nanoTime();try {if (parent != null) {// 如果父加载不为空,那么由父加载器加载// 迭代c = parent.loadClass(name, false);} else {// 由 Bootstrap ClassLoader 加载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();// 由子类加载器尝试加载c = findClass(name);// this is the defining class loader; record the statsPerfCounter.getParentDelegationTime().addTime(t1 - t0);PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);PerfCounter.getFindClasses().increment();}}if (resolve) {resolveClass(c);}return c;}
}
为什么需要破坏双亲委派
在实际应用中,双亲委派解决了 Java 基础类统一加载的问题,但是去存在着缺陷。JDK 中的基础类作为典型的 api 被用户调用,但也存在 api 调用用户代码的情况,典型的如:SPI 代码。这种情况就需要打破双亲委派模式。
数据库驱动 DriverManager 。以 Driver 接口为例,Driver 接口定义在 JDK 中,其实现由各个服务厂商 来提供,由系统类加载器加载。 这个时候就需要 启动类加载器 来 委托 子类来加载 Driver 实现,这也算破坏了双亲委派。
深入DriverManager如何破坏双亲委派
测试代码如下
import java.sql.DriverManager;
import java.sql.SQLException;public class Test {public static void main(String[] args) throws ClassNotFoundException, SQLException {System.out.println(DriverManager.class.getClassLoader());DriverManager.getConnection("jdbc:mysql//localhost:3036/db", "test", "test");}
}
源码流程如下图:
注意此流程图
jdk 8
调试涉及的内容
由上可知,DriverManager 并未走双亲委派来加载 mysql 的实现类,而是由父加载器指派子加载器进行加载。
注意: jdk 17中有明确的 ClassLoader platform 而在 jdk 8中却是 null
如何破坏双亲委派
一般有以下三种:
- 1.重写ClassLoader 的 loaderClass 方法
- 2.SPI ,父类委托自类加载器加载 Class ,以数据库驱动 DriverManger 为例
- 3.热部署和不停机更新用到的OSGI技术
结束
至此,双亲委派模型与打破双亲委派就结束了,如有疑问,欢迎评论区留言。
更多推荐
3.双亲委派模型与打破双亲委派
发布评论