【JVM学习笔记】线程上下文类加载器

有许多地方能够看到线程上下文类加载的设置,比如在sun.misc.Launcher类的构造方法中,能够看到如下代码

先写一个例子建立感性认识

public class Test {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getContextClassLoader());
        System.out.println(Thread.class.getClassLoader());
    }
}

输出

sun.misc.Launcher$AppClassLoader@18b4aac2
null

这是因为Thread类位于rt.jar包,而当前线程的上下文加载器,也就是加载了main函数所在类的加载器,其实就是系统类加载器

当前类加载器(Current ClassLoader)的概念

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

线程上下文类加载器(Context ClassLoader)

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

如果没有通过setContextClassLoader(ClassLoader cl)进行设置的话,线程将继承其父线程的上下文类加载器。

Java应用运行时的初始线程的上下文加载器是系统类加载器。线程中运行的代码,可以通过该类加载器来加载类与资源。

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

 

猜你喜欢

转载自www.cnblogs.com/heben/p/11455768.html
今日推荐