天天看点

双亲委派模型推荐公众号参考书籍什么是类加载器类与类加载器类加载模型双亲委派模型:破坏双亲委派模型

目录

  • 推荐公众号
  • 参考书籍
  • 什么是类加载器
  • 类与类加载器
  • 类加载模型
    • 启动类加载器Bootstrap ClassLoader
    • 扩展类加载器Extension ClassLoader
    • 应用程序类加载器Application ClassLoader
  • 双亲委派模型:
  • 破坏双亲委派模型

推荐公众号

有彩蛋哦!!!(或者公众号内点击网赚获取彩蛋)

双亲委派模型推荐公众号参考书籍什么是类加载器类与类加载器类加载模型双亲委派模型:破坏双亲委派模型

参考书籍

深入理解Java虚拟机 第二版 周志明著

什么是类加载器

JVM设计团队主张把类加载阶段”通过一个类的全限定名来获取此类的二进制字节流”这个动作放到JVM外部去实现,

以便让应用程序自己决定如何去获取所需要的类。实现这个动作的代码模块称为“类加载器”。

类与类加载器

类加载器虽然只用于实现类的加载动作,但它在java程序中起到的作用却远远不限定于类加载阶段。对于任意一个类,

都需要有加在他的类加器器和这个类本身一同确立其在JVM中的唯一性,每一个类加载器,都拥有一个独立的类名称空间。

表达的再简单一点就是:比较两个类是否相等,只有在这两个类是有同一类加载器加载的前提下才有意义,否则即使这两个类源于统一class文件,别同一个JVM加载,只要加载他们的类加载器不一样,这两个类就不相等。这里指的相等,包括代表类的class对象的equals方法,isAssignableFrom方法,isInstance方法的返回结果;还有instanceof关键字的判定情况。

类加载模型

从JVM角度讲,只有两种不同的类加载器:启动类加载器Bootstrap ClassLoader,这个类加载器是有c++语言实现的,是JVM自身的一部分;其他类加载器,

这些类加载器都有java语言实现,独立于JVM外部,并且全部继承自java.lang.ClassLoader。从开发人员角度讲,类加载器还有更细致的划分,同时这个层次关系也叫类加载器的双亲委外模型

​​​​

双亲委派模型推荐公众号参考书籍什么是类加载器类与类加载器类加载模型双亲委派模型:破坏双亲委派模型

注意:图上给出的箭头只是说明层次上的定义,并不是绝对的(有的是有的不是)继承关系;

启动类加载器Bootstrap ClassLoader

是JVM的一部分,负责加载的是JAVA_HOME/lib下的类库,或者被-Xbootclasspath参数所指定的路径中的并且是JVM识别的(仅按照文件名识别,如rt.jar,名字不符合的类库即使放在lib目录中也不会被加载),启动类加载器无法被JAVA程序直接应用

扩展类加载器Extension ClassLoader

这个类加载由sum.misc.Launcher$ExtClassLoader实现,它负责用于加载JAVA_HOME/lib/ext目录中的,或者被java.ext.dirs系统变量指定所指定的路径中的所有类库,开发者可以直接使用扩展类加载器。Java.ext.dirs系统变量指定的路径可以通过

System.getProperty("java.ext.dirs")

D:\java\jdk\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
           

应用程序类加载器Application ClassLoader

这个类加载器由sun.misc.Launcher$AppClassLoader实现。别名:系统类加载器,如果应用程序中没有自定义过自己的类加载器,一般情况下这个就是程序中默认的类加载器

public static void main(String[] args) {
   System.out.println(ClassLoader.getSystemClassLoader());
}
sun.misc.Launcher$AppClassLoader@18b4aac2

父加载器
public static void main(String[] args) {
        System.out.println(ClassLoader.getSystemClassLoader().getParent());
    }
sun.misc.Launcher$ExtClassLoader@77468bd9

ExtClassLoader的父加载器
public static void main(String[] args) {
        System.out.println(ClassLoader.getSystemClassLoader().getParent().getParent());
    }
 结果: null
           

双亲委派模型:

工作过程:如果一个类加载器收到了类加载器的请求,他首先不会自己去尝试加载这个类,而是把这个请求委派给父类加载器去完成,每一个层次的类加载器都是如此,因此所有的加载请求最终都应该传送到顶层的启动类加载器中,只有当类加载器反馈自己无法完成这个加载请求(他的搜索范围中没有找到所需的类)时,子加载器才会尝试自己去加载。

双亲委派模型的好处:使用双亲委派模型来组织类的加载器之间的关系,能使java类随着他的类加载器一起具备了一种带有优先级的层次关系。例如类java.lang.Object,它存放在rt.jar中,无论哪一个类加载器要加载这个类,最终都是委派给处于模型最顶端的启动类加载器进行加载,因此java.lang.Object类在程序的各种类加载器环境中都是同一个类。

双亲委派模型代码实现 java.langClassLoader loadClass方法

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.
                调用自身的findClass方法
                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;
    }
}
           

破坏双亲委派模型

书中举得例子有三种,我举个最常用得例子

JNDI服务 例如 JDBC

SPI Service Provider Interface 服务提供者

JNDI服务在rt.jar中,应该由启动类加载器去加载,但是JNDI得接口提供者是各个厂商,在应用程序得ClassPath下,启动类加载器哪里会知道这些代码,这些代码应该由应用程序类加载器来完成。

为了解决这个问题,引入了线程上下文类加载器(Thread Context ClassLoader)。这个类加载器可以通过java.lang.Thread.setContextClassLoaser()方法设置,如果创建线程未设置则从父线程中继承一个,如果在应用程序得全局范围内都没有设置的话,那这个类加载器默认是应用程序类加载器。那么JNDI来说就是父加载器调用子加载器来完成加载,就是打通了双亲委派模型的层次结构来逆向使用类加载器,违背了双亲委派模型的一般性原则。

JDBC SPI为例子

通过SPI方式加载JDBC

try {
            conn = (Connection)DriverManager.
            getConnection(url, user, passwd);
    } catch (Exception e) {
            System.out.println(e);
    }
           
java.sql.DriverManger
/**
     * Load the initial JDBC drivers by checking the System property
     * jdbc.properties and then use the {@code ServiceLoader} mechanism
     */
    static {
        loadInitialDrivers();
        println("JDBC DriverManager initialized");
    }

private static void loadInitialDrivers() {
先读取系统属性  如果没有设置的话 显然 获取出来的是null
        String drivers;
        try {
            drivers = AccessController.doPrivileged(
            new PrivilegedAction<String>() {
                public String run() {
                    return System.getProperty("jdbc.drivers");
                }
            });
        } catch (Exception ex) {
            drivers = null;
        }
        // If the driver is packaged as a Service Provider, load it.
        // Get all the drivers through the classloader
        // exposed as a java.sql.Driver.class service.
        // ServiceLoader.load() replaces the sun.misc.Providers()
		SPI 注册
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
				注意这个 获取的ClassLoader
                ServiceLoader<Driver> loadedDrivers = 
                ServiceLoader.load(Driver.class);
                Iterator<Driver> driversIterator = loadedDrivers.iterator();

                /* Load these drivers, so that they can be instantiated.
                 * It may be the case that the driver class may not be there
                 * i.e. there may be a packaged driver with the service class
                 * as implementation of java.sql.Driver but the actual class
                 * may be missing. In that case a java.util.ServiceConfigurationError
                 * will be thrown at runtime by the VM trying to locate
                 * and load the service.
                 *
                 * Adding a try catch block to catch those runtime errors
                 * if driver not available in classpath but it's
                 * packaged as service and that service is there in classpath.
                 */
                try{
                    while(driversIterator.hasNext()) {
                    	.next中实现注册
                        driversIterator.next();
                    }
                } catch(Throwable t) {
                // Do nothing
                }
                return null;
            }
        });

        println("DriverManager.initialize: jdbc.drivers = " + drivers);

        if (drivers == null || drivers.equals("")) {
            return;
        }
        String[] driversList = drivers.split(":");
        println("number of Drivers:" + driversList.length);
        for (String aDriver : driversList) {
            try {
                println("DriverManager.Initialize: loading " + aDriver);
                Class.forName(aDriver, true,
                        ClassLoader.getSystemClassLoader());
            } catch (Exception ex) {
                println("DriverManager.Initialize: load failed: " + ex);
            }
        }
    }

/**
     * Creates a new service loader for the given service type, using the
     * current thread's {@linkplain java.lang.Thread#getContextClassLoader
     * context class loader}.
     *
     * <p> An invocation of this convenience method of the form
     *
     * <blockquote><pre>
     * ServiceLoader.load(<i>service</i>)</pre></blockquote>
     *
     * is equivalent to
     *
     * <blockquote><pre>
     * ServiceLoader.load(<i>service</i>,
     *                    Thread.currentThread().getContextClassLoader())</pre></blockquote>
     *
     * @param  <S> the class of the service type
     *
     * @param  service
     *         The interface or abstract class representing the service
     *
     * @return A new service loader
     */
     ServerLoader.java
     可以看到是用的线程上下文加载器
    public static <S> ServiceLoader<S> load(Class<S> service) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        return ServiceLoader.load(service, cl);
    }
    
private S nextService() {
    if (!hasNextService())
        throw new NoSuchElementException();
    String cn = nextName;
    nextName = null;
    Class<?> c = null;
    try {
        加载实现类,还没有初始化;以JDBC为例,此时还没有完成驱动注册
        c = Class.forName(cn, false, loader);
    } catch (ClassNotFoundException x) {
        fail(service,
             "Provider " + cn + " not found");
    }
    service就是SPI,以JDBC为例,service就是Java Driver接口;此处判断c是否为
    Driver的实现
    if (!service.isAssignableFrom(c)) {
        fail(service,
             "Provider " + cn  + " not a subtype");
    }
    try {
        c是spi的实现,c.newInstance()会触发类的初始化动作,以JDBC为例,这一操作
        完成驱动注册
        S p = service.cast(c.newInstance());
        providers.put(cn, p);
        return p;
    } catch (Throwable x) {
        fail(service,
             "Provider " + cn + " could not be instantiated",
             x);
    }
    throw new Error();          
    // This cannot happen
}
           

为了对比 写一下通过系统属性注册驱动

try {
            System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");
            conn = (Connection)DriverManager.
            getConnection(url, user, passwd);
    } catch (Exception e) {
            System.out.println(e);
    }
    那下面就清楚,设置玩系统属性
    static {
        loadInitialDrivers();
        println("JDBC DriverManager initialized");
    }

private static void loadInitialDrivers() {
先读取系统属性  如果没有设置的话 显然 获取出来的是null
        String drivers;
        try {
            drivers = AccessController.doPrivileged(
            new PrivilegedAction<String>() {
                public String run() {
                    return System.getProperty("jdbc.drivers");
                }
            });
        } catch (Exception ex) {
            drivers = null;
        }
        // If the driver is packaged as a Service Provider, load it.
        // Get all the drivers through the classloader
        // exposed as a java.sql.Driver.class service.
        // ServiceLoader.load() replaces the sun.misc.Providers()
		SPI 注册
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
				注意这个 获取的ClassLoader
                ServiceLoader<Driver> loadedDrivers = 
                ServiceLoader.load(Driver.class);
                Iterator<Driver> driversIterator = loadedDrivers.iterator();

                /* Load these drivers, so that they can be instantiated.
                 * It may be the case that the driver class may not be there
                 * i.e. there may be a packaged driver with the service class
                 * as implementation of java.sql.Driver but the actual class
                 * may be missing. In that case a java.util.ServiceConfigurationError
                 * will be thrown at runtime by the VM trying to locate
                 * and load the service.
                 *
                 * Adding a try catch block to catch those runtime errors
                 * if driver not available in classpath but it's
                 * packaged as service and that service is there in classpath.
                 */
                try{
                    while(driversIterator.hasNext()) {
                    	.next中实现注册
                        driversIterator.next();
                    }
                } catch(Throwable t) {
                // Do nothing
                }
                return null;
            }
        });

        println("DriverManager.initialize: jdbc.drivers = " + drivers);

        if (drivers == null || drivers.equals("")) {
            return;
        }
        String[] driversList = drivers.split(":");
        println("number of Drivers:" + driversList.length);
        for (String aDriver : driversList) {
            try {
                println("DriverManager.Initialize: loading " + aDriver);
                Class.forName(aDriver, true,
                        ClassLoader.getSystemClassLoader());
            } catch (Exception ex) {
                println("DriverManager.Initialize: load failed: " + ex);
            }
        }
    }