Mutant World

Thursday, July 13, 2006

Why Thread.currentThread().getContextClassLoader() ?

I recently been involved in a discussion where I questioned that Thread.currentThread().getContextClassLoader() was the right way to implement the accessibility of a ClassLoader from any point in the code from a thread.
I very much preferred that ClassLoader.getContextClassLoader() was available, thus freeing class Thread of any reference to class loading.

Other examples of accessibility of thread local information are present in the Java libraries, most notably TransactionManager.getTransaction(), that returns the Transaction currently associated with the thread (though the call is not static).
There is also a RFE for having the Locale available, see RFE 6197800.

Both follow the model of not being implemented in class Thread, so I wonder why for ClassLoader it was implemented in this way. Some historical reason maybe, and probably right now is not practical to deprecate that call in favor of ClassLoader.getContextClassLoader().


  • It is useful for environment propogation into the base classes. Weblogic used it quite a bit.

    I think one of the examples was where you used RMI and the thread's classloader was network aware and could get the class definition from the host.

    Basically, you don't need it normally, but when you need it you really do need it.

    By Blogger BlogicBlogger, at 13 July, 2006 21:13  

  • This is a great interview question I like to ask :)

    Did you ever wonder why you need to call Class.forName() to load JDBC driver but don't have to for JNDI, which appeared in Java 2 at the same time when Context Classloader was introduced?

    Here is the answer. When a classloader loads classes, it asks the parent classloader to load, only if the class is not available, it tries to load it.
    In the case of API, such as JNDI, the parent classloader usualy can load JNDI classes, but only child classloader can load JNDI implementation, such as J2EE server client library.
    So, standart classloading mechanism doesn't work. That is why we need context classloader. JNDI API is using it to load JNDI implementation classes from child classloader!

    Hope it helps.

    By Anonymous Anonymous, at 14 July, 2006 17:46  

Post a Comment

<< Home