views:

147

answers:

2

Why is the setContextClassLoader() method placed on Thread?

What different thread have different classloaders?

The question is what if I extended a ClassLoader, loaded there some new classes. to the my custom classloader.

Now , I want it to be the context classloader , so I call the method Thread.currentThread().setContextClassLoader(loader).

Are these new classes awailable only in the context of the current thread ? Or how does it work?

Thanks

+1  A: 

The Context class loader is the class loader that the thread will use to find classes. You primarily care about this when you are writing an application server or something similar. The idea is that you can start a thread from a class loaded in the application server's class loader, and yet pass it a child class loader that handles loading the classes of the deployed application.

Yishai
A: 

The thread context class loader is a little bit of a hack.

When you load a class with reflection, you use either an explicit class loader or the one of the immediate calling class. When you link to a class using normal Java code, then class requesting the linking is used as the source for the loader.

Thread.setContextClassLoader is used to set the class loader for Thread.getContextClassLoader. This is used by random APIs (notably through ServiceLoader) to pick up classes through reflection so that you can change implementation. Having implementations change out from under your code depending upon which thread it is running on at a crucial moment is a bad idea.

Tom Hawtin - tackline