简体   繁体   English

类加载器在多个线程中的行为

[英]The behavior of the classloader in multiple threads

How to understand that 如何理解

In a multi-threaded environment you might have type conversion exceptions due to different classloaders 在多线程环境中,由于不同的类加载器,您可能会有类型转换异常

I saw the source code of Spring about this: 我看到了Spring的源代码:

public static ClassLoader getDefaultClassLoader() {
    ClassLoader classLoader = null;
    try {
        classLoader = Thread.currentThread().getContextClassLoader();
    } catch (Throwable ex) {
        ex.printStackTrace();
    }
    if (classLoader == null) {
        // No thread context class loader -> use class loader of this class
        classLoader = ClassUtil.class.getClassLoader();
        if (classLoader == null) {
            // getClassLoader() returning null indicates the bootstrap ClassLoader
            try {
                classLoader = ClassLoader.getSystemClassLoader();
            } catch (Throwable ex) {

            }
        }
    }
    return classLoader;
}

I don't why they chose Thread.currentThread().getContextClassLoader() to be the first choice? 我为什么不选择Thread.currentThread()。getContextClassLoader()作为首选?

Someone told me cause the behavior of classloader could be different in multi-thread 有人告诉我,原因是在多线程中类加载器的行为可能不同

To be honest, I can't understand 老实说,我听不懂

Thread.currentThread().getContextClassLoader() would be the natural first choice, so that different contexts can reliably set their private classloader overrides. Thread.currentThread()。getContextClassLoader()是自然的首选,因此不同的上下文可以可靠地设置其私有类加载器重写。 While most often additional classloaders are used for loading classes that are not provided by the lower-level classloaders, another use would be to use specific implementations of some classes in some contexts. 尽管大多数情况下,额外的类加载器用于加载较低级别的类加载器未提供的类,但另一种用法是在某些情况下使用某些类的特定实现。

When this is combined with the fact that the type identity of a class contains the classloader that loaded the class, it becomes possible to have two classes of the same (absolute) class name that still are not of the same type. 当这与类的类型标识包含已加载该类的类加载器的事实结合时,就有可能使两个具有相同(绝对)类名称的类仍然不是同一类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM