Difference between Thread.currentThread() classLoader and normal classLoader

Thread.currentThread().getContextClassLoader()

Returns the context ClassLoader for this Thread. The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If not set, the default is the ClassLoader context of the parent Thread. The context ClassLoader of the primordial thread is typically set to the class loader used to load the application.

Class#getClassLoader()

Returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.


In a nutshell:

Thread.currentThread().getContextClassLoader() is the ClassLoader of the context of the thread that has been set with setContextClassLoader(ClassLoader cl). Imagine that you have a complex java application with a hierarchy of ClassLoader (for example an Application Server) and you want your current thread to load classes or resources from one specific ClassLoader in this hierarchy, you can do it by simply setting the context ClassLoader of the thread to this specific ClassLoader.

Class#getClassLoader() is simply the ClassLoader from which your instance of Class has been loaded.


Thread.currentThread().getContextClassLoader()

This is the current thread classloader and doesn't depend on the class calling it

TestServlet.class.getClassLoader()

This is the classloader that loaded the TestServlet class.

please explain as well as provide me example when to use these

Let's imagine you have Thread1 owned by ClassLoader1 and Thread2 owned by ClassLoader2. It's possible that you load your TestServlet class on Thread2 (by ClassLoader2) and then pass it to Thread1. At that point, if TestServlet needs to load a Class owned by ClassLoader1 it will need to use Thread.currentThread().getContextClassLoader(), as it's own ClassLoader is ClassLoader2 and not ClassLoader1.