Monday, 11 March 2013

Why Do we need ContextClassLoader

ContextClassLoader is the subject which is very little known and very useful.

Some basics about class and classloader in java :

Every Object in java has associated Class Object which defines its class meta data and stored in a separate space called perm gen in java memory. infect, every type in java[primitive or user defined] has a class objects ,even keyword void in java has a class object.
Classloader are the objects which loads the class from file system and converts the byte code in the file to Class Object.It preserves the class object in the cache , so the classloader doesn't have to load and define it again. Classloaders in java follows hierarchical structure, where a child classloader first checks whether the class is already loaded by parent classloader, if not then only it loads the class.

ContextClassLoader :

Image here represnts a simple classloader architecture for a container , this is very simple architecture and the actual architecture of the server may be more complex than this.

So the top three classloader are java defined classloader which loads classes from rt.jar , ext library and classpath respectively.and below that server classloader are present which loads server specific classes and then application specific classes .
For each application , server creates a new classloader. because of this hierarchical structure that classloader follows [untill somebody creates a custom classloader which deliberately breaks classloader rules], parent classloader can never see the classes which are loaded by child classloader. Now in some condition we need to load class which is loaded by child classloader , in to the class which is loaded by parent classloader.
For example , in JNDI classes which are loaded by java classloaders , we need to load web application specific classes.That is where ContextClassloader comes in to the picture , which provides a hook in to other classloaders which are otherwise not accessible to higher level classloaders . So every server sets it's web application classloader in the Thread class , so that other classes can get hold of this classloader.
Ref