Why do we need contexClassLoader

102 Views Asked by At

I'm wondering why Java introduced contexClassLoader for threads. I know that it is usualy used by frameworks and application servers which have to dynamically find and load classes.

However I don't understand why Java introduced contexClassLoader when we can achieve the same functionality simply by adding field that will hold necessary class loader.

class ThreadWithCustomClassloader extends Thread
{
    ClassLoader threadClassLoader;

    public void run()
    {
       //use threadClassLoader to dynamically find and load classes
    }
}
2

There are 2 best solutions below

5
On

I'm confused - having an instance variable for the class loader is exactly what the Thread class uses to implement this. What's different in your solution?

Do you mind about the setter? Setting the class loader is important to be able to reuse the same thread (e.g. in the servlet container) for a completely different environment (web application). Thread instances are considered expensive...

0
On

The default class loader mechanism in JVM is parent delegation, Thread context classloaders provide a back door around the classloading delegation scheme. Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

For more information, please check which class loader should you use