2

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.

sidhartha pani
  • 623
  • 2
  • 12
  • 23

1 Answers1

3

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);
} 
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
  • Tomcat uses this to set the WebApplicationClassloader. So, it is used in web applications I believe. – Jyothi Apr 21 '22 at 05:43