Difference between Thread.currentThread () classLoader and regular 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 explain and give me an 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"); } } 
+11
source share
2 answers

Thread.currentThread().getContextClassLoader()

Returns the ClassLoader context for this Thread . The ClassLoader context ClassLoader provided by the creator of the stream for use by the code that runs on this stream when classes and resources are loaded. If not set, the default is the ClassLoader context of the parent thread. The ClassLoader context from the primary stream is usually 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 bootloader classes. This method will return null in such implementations if this class was loaded by the class loader loader.


In a nutshell:

Thread.currentThread().getContextClassLoader() is the ClassLoader the thread context that was set using setContextClassLoader(ClassLoader cl) . Imagine that you have a complex Java application with a ClassLoader hierarchy (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 this simply by setting the ClassLoader context of the stream for this particular ClassLoader .

Class#getClassLoader() is just the ClassLoader from which your instance of Class was loaded.

+8
source

Thread.currentThread (). GetContextClassLoader ()

This is the current stream classloader and is independent of the class that calls it.

TestServlet.class.getClassLoader ()

This is the class loader that loaded the TestServlet class.

explain and also give an example of using these

Suppose you have Thread1 owned by ClassLoader1, and Thread2 owned by ClassLoader2. Perhaps you load your TestServlet class into Thread2 (using ClassLoader2) and then pass it to Thread1. At this point, if a TestServlet needs to load a Class belonging to ClassLoader1, it will need to use Thread.currentThread (). GetContextClassLoader () since its own ClassLoader is ClassLoader2, not ClassLoader1.

+4
source

Source: https://habr.com/ru/post/1258936/


All Articles