Java中类加载器双亲委派机制,及打破双亲委派机制

一、双亲委派

原理图

核心代码

//ClassLoader的loadClass方法,里面实现了双亲委派机制
protected Class<?> loadClass(String name, boolean resolve)
 throws ClassNotFoundException
{
 synchronized (getClassLoadingLock(name)) {
 // 检查当前类加载器是否已经加载了该类
 Class<?> c = findLoadedClass(name);
 if (c == null) {
 long t0 = System.nanoTime();
  try {
  if (parent != null) { //如果当前加载器父加载器不为空则委托父加载器加载该类
  c = parent.loadClass(name, false);
  } else { //如果当前加载器父加载器为空则委托引导类加载器加载该类
  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();
  //都会调用URLClassLoader的findClass方法在加载器的类路径里查找并加载该类
  c = findClass(name);

  // this is the defining class loader; record the stats
  sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 ‐ t0);
  sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
  sun.misc.PerfCounter.getFindClasses().increment();
  }
  }
  if (resolve) { //不会执行
  resolveClass(c);
  }
  return c;
  }
 }

为什么要设计双亲委派机制?

  • 沙箱安全机制:自己写的java.lang.String.class类不会被加载,这样便可以防止核心API库被随意篡改
  • 避免类的重复加载:当父亲已经加载了该类时,就没有必要子ClassLoader再加载一次,保证被加载类的唯一性

二、打破双亲委派的方法

打破双亲为委派需要自定义类加载器,自定义类加载器只需要继承 java.lang.ClassLoader 类,该类有两个核心方法,一个是loadClass(String, boolean),实现了双亲委派机制,还有一个方法是findClass,默认实现是空方法,所以我们自定义类加载器主要是重写findClass方法。

三、应用场景

tomcat一个容器加载多个war包,每个war有自己单独的类加载器webAppClassLoader。

模拟实现Tomcat的webappClassLoader加载自己war包应用内不同版本类实现相互共存与隔离

1 public class MyClassLoaderTest {
2  static class MyClassLoader extends ClassLoader {
3  private String classPath;
4
5  public MyClassLoader(String classPath) {
6  this.classPath = classPath;
7  }
8
9  private byte[] loadByte(String name) throws Exception {
10  name = name.replaceAll("\\.", "/");
11  FileInputStream fis = new FileInputStream(classPath + "/" + name
12  + ".class");
13  int len = fis.available();
14  byte[] data = new byte[len];
15  fis.read(data);
16  fis.close();
17  return data;
18
19  }
20
21  protected Class<?> findClass(String name) throws ClassNotFoundException {
22  try {
23  byte[] data = loadByte(name);
24  return defineClass(name, data, 0, data.length);
25  } catch (Exception e) {
26  e.printStackTrace();
27  throw new ClassNotFoundException();
28  }
29  }
30
31  /**
32  * 重写类加载方法,实现自己的加载逻辑,不委派给双亲加载
33  * @param name
34  * @param resolve
35  * @return
36  * @throws ClassNotFoundException
37  */
38  protected Class<?> loadClass(String name, boolean resolve)
39  throws ClassNotFoundException {
40  synchronized (getClassLoadingLock(name)) {
41  // First, check if the class has already been loaded
42  Class<?> c = findLoadedClass(name);
43
44  if (c == null) {
45  // If still not found, then invoke findClass in order
46  // to find the class.
47  long t1 = System.nanoTime();
48
49  //非自定义的类还是走双亲委派加载
50  if (!name.startsWith("com.tuling.jvm")){
51  c = this.getParent().loadClass(name);
52  }else{
53  c = findClass(name);
54  }
55
56  // this is the defining class loader; record the stats
57  sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
58  sun.misc.PerfCounter.getFindClasses().increment();
59  }
60  if (resolve) {
61  resolveClass(c);
62  }
63  return c;
64  }
65  }
66  }
67
68  public static void main(String args[]) throws Exception {
69  MyClassLoader classLoader = new MyClassLoader("D:/test");
70  Class clazz = classLoader.loadClass("com.tuling.jvm.User1");
71  Object obj = clazz.newInstance();
72  Method method= clazz.getDeclaredMethod("sout", null);
73  method.invoke(obj, null);
74  System.out.println(clazz.getClassLoader());
75
76  System.out.println();
77  MyClassLoader classLoader1 = new MyClassLoader("D:/test1");
78  Class clazz1 = classLoader1.loadClass("com.tuling.jvm.User1");
79  Object obj1 = clazz1.newInstance();
80  Method method1= clazz1.getDeclaredMethod("sout", null);
81  method1.invoke(obj1, null);
82  System.out.println(clazz1.getClassLoader());
83  }
84 }
85
86 运行结果:
87 =======自己的加载器加载类调用方法=======
88 com.tuling.jvm.MyClassLoaderTest$MyClassLoader@266474c2
89
90 =======另外一个User1版本:自己的加载器加载类调用方法=======
91 com.tuling.jvm.MyClassLoaderTest$MyClassLoader@66d3c617

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值