JVM 线程上下文类加载器

当前类加载器(Current ClassLoader)
每个类都会使用自己的类加载器(即加载自身的类加载器)来去加载其他类(指所依赖的类)
如果ClassX引用了ClassY,那么ClassX的类加载器就会去加载ClassY(前提是ClassY尚未被加载)

线程上下文加载器(Context Classloader)
线程上下文加载器是从JDK1.2开始引入,类Thread中的getContextLoader() 与setContextClassLoader(ClassLoader cl)
分别用来获取和设置上下文类加载器

如果没有通过setContextClassLoader(ClassLoader cl)进行设置的话,线程将继承其父线程的上下文加载器。
Java 应用运行时的初始线程的上下文加载器是系统类加载器。在线程中运行的代码可以通过该类加载器来加载类与资源。

线程上下文加载器的重要性

SPI(Service Provider Interface)如JDBC
父ClassLoader可以使用当前线程Thread.currentThread().getContextClassLoader()所指定的classLoader加载的类
这就改变了父ClassLoader不能使用子ClassLoader或是或者其它没有父子关系的ClassLoader加载的类的情况,即改变了双亲委托模型

线程上下文类加载器就是当前线程的Current ClassLoader

如下面代码是连接使用JDBC连接Oralce

Connection是在rt.jar中的package java.sql;下,由启动类加载器加载。

具体Connection的实现是有Oracle厂商实现,会由AppClassLoader加载。

这样会导致的问题,启动类加载器加载的类不能访问AppClassLoader加载的类。

在双亲委托模型下,类的加载是由下至上的,即下层的类加载器会委托上层进行加载。但对于SPI来说,有些接口是Java核心库所提供的,
而Java核心库是由启动类加载器来加载的,而这些接口的实现却来自不同的Jar包(厂商提供JDBC的实现有Oracle,MySQL等), Java的启动类加载器不会加载其他
来源的jar包,这样传统的双亲委托模型就无法满足SPI的要求。而通过给当前线程设置上下文类加载器,就可以由设置的上下文类加载器
来实现对于接口实现类的加载。

1、创建MyTest24.java类

public class MyTest24 {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getContextClassLoader()); //AppClassLoader
        System.out.println(Thread.class.getClassLoader()); //null 启动类加载器
    }
}

  输出结果:

sun.misc.Launcher$AppClassLoader@18b4aac2
null

  

猜你喜欢

转载自www.cnblogs.com/linlf03/p/11069014.html
今日推荐