Search code examples
javamultithreadingclassloader

Difference between Thread.currentThread() classLoader and normal classLoader


Can you tell me what is the difference between Thread.currentThread().getContextClassLoader() and TestServlet.class.getClassLoader() do not mark it as duplicate and also please explain as well as provide me example when to use these

Java File:

package com.jar.test;

public class TestServlet {
    public static void main(String args[]) {    
        ClassLoader cls = TestServlet.class.getClassLoader().loadClass(
                "com.jar.test.TestServlet");
        ClassLoader cls = Thread.currentThread().getContextClassLoader()
                .loadClass("com.jar.test.TestServlet");
    }
}

Solution

  • 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.