JVM双亲委派机制

双亲委派模型

源码

public abstract class ClassLoader {
  private final ClassLoader parent;
      protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
        synchronized (getClassLoadingLock(name)) {
            // First, check if the class has already been loaded
            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();
                    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;
        }
    }
}

从源码得知,加载器关系为上下级,而非继承。

  • 启动类加载器(Bootstrap ClassLoader)
    • 加载Jre/lib/rt.jar
  • 扩展类加载器(Extension ClassLoader)
    • 加载Jre/lib/ext/*.jar
  • 应用程序类加载器(Application ClassLoader)
    • 加载CLASS_PATH指定目录下的所有Jar

双亲委派优点:

  • 双亲委派机制保护了类不会被重复加载
  • 加载机制提供沙箱机制,禁止用户污染java开头的核心包
posted @ 2021-09-04 15:17  Richard·Lee  阅读(59)  评论(0)    收藏  举报