Difference between thread's context class loader and normal classloader

abracadabra picture abracadabra · Nov 20, 2009 · Viewed 108k times · Source

What is the difference between a thread's context class loader and a normal class loader?

That is, if Thread.currentThread().getContextClassLoader() and getClass().getClassLoader() return different class loader objects, which one will be used?

Answer

David Roussel picture David Roussel · Nov 20, 2009

Each class will use its own classloader to load other classes. So if ClassA.class references ClassB.class then ClassB needs to be on the classpath of the classloader of ClassA, or its parents.

The thread context classloader is the current classloader for the current thread. An object can be created from a class in ClassLoaderC and then passed to a thread owned by ClassLoaderD. In this case the object needs to use Thread.currentThread().getContextClassLoader() directly if it wants to load resources that are not available on its own classloader.