Thread Context Class Loader vs. Normal Class Loader
Java provides two distinct mechanisms for class loading: the thread's context class loader and the normal class loader.
Thread's Context Class Loader
The context class loader is a class loader associated with each thread. It is used when a thread needs to load a class dynamically, such as when using reflection or deserialization. By default, the context class loader is set to the parent class loader of the class loader that loaded the thread's main class.
Normal Class Loader
The normal class loader is the class loader used to load classes for the current class. It is retrieved using the getClass().getClassLoader() method. Typically, the normal class loader is the same as the context class loader, meaning it is the parent class loader of the class loader that loaded the main class.
Which Class Loader is Used?
When a thread loads a class dynamically, it typically uses the context class loader. However, if the thread's context class loader is different from the normal class loader, which one is used depends on the context.
Only in specific circumstances can the normal class loader be used instead of the context class loader. For instance, if the context class loader is null, the normal class loader is utilized.
Recommendation
Generally, it is recommended to use the normal class loader (i.e., getClass().getClassLoader()) when loading classes explicitly, even if the context class loader is different. Explicit class loading should always use the class loader of the class performing the loading.
The above is the detailed content of Thread Context Class Loader vs. Normal Class Loader: When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!