sidhartha pani sidhartha pani - 2 months ago 20
Java Question

When to use Thread.currentThread().getContextClassLoader() in webapplications

Hi can someone tell me when to use

Thread.currentThread().getContextClassLoader()

in web application .Please provide me some real life example. Please do not mark it as duplicate question(My question is when to use Thread.currentThread().getContextClassLoader() and, not for loading properties file) . I have gone through many sites but I did not get proper answer.

Answer

First of all, please note that this method is not something Java EE related, it is a method of Java SE so it is not something that is meant to be used in web applications only but potentially in any Java applications.

We generally use this method with Thread.currentThread().setContextClassLoader(ClassLoader) in order to check and/or change the context ClassLoader of the calling thread.

So typically let's say that you are writing a Java Application that will need a custom ClassLoader that loads classes from specific folders and/or jar files that where not initially on the classpath, you would use these methods to change of context ClassLoader and restore the previous CL. This will allow your code to access to classes that where not accessible previously from the current context CL as they were not on the classpath initially.

So here is how your code would look like:

// The previous context ClassLoader
final ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
try {
    // Set my custom ClassLoader to make my classes accessible
    Thread.currentThread().setContextClassLoader(myCustomCL);
    // Execute some code here that will be able to access to classes or resources from
    // my specific folders and/or jar files

} finally {
    // Restore the previous CL
    Thread.currentThread().setContextClassLoader(contextCL);
}