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:
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?
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.