Wednesday, January 27, 2010

Java ClassLoader Architecture - Understanding Java Classloaders

The architecture of Java ClassLoader is hierarchical in nature. At the root of the hierarchy is the ‘Bootstrap’ classloader followed by ‘extension’ classloader and eventually the ‘sytem’(application) classloader. This means that ClassLoaders form a hierarchical tree, with the “bootstrap” ClassLoader as the root of the Tree.

Java ClassLoader model is a “delegating parent” model. What this means is that when a ClassLoader is asked to load a class, it first delegates the opportunity to load the requested class to its parent ClassLoader. Only if the parent classloader has not already loaded the Class does the child ClassLoader get the opportunity to load the Class requested.

The Java system provides for loading code from one of three places: one, the core library, second, the Extensions directory (or directories, if you modify the java.ext.dirs property to include multiple subdirectories), and lastly from the directories and .jar/.zip files found along the java.class.path property, which in turn comes from the CLASSPATH environment variable. Each of these three locations is in turn covered by its own ClassLoader instance: the core classes, by the bootstrap ClassLoader, the Extensions directory/directories by the extension ClassLoader, and the CLASSPATH by the system or application ClassLoader.

I hope you guys must have got an overall idea of how the classes are loaded in java.

Now for some recap:

The bootstrap ClassLoader is implemented as part of the VM itself . It is this ClassLoader that brings the core Java classes into the
VM, thereby, allowing the rest of the JVM to load itself. Normally, this means loading code from the “rt.jar” file in the jdk/jre/lib subdirectory, but under the JVM, the boot.class.path system property actually controls it.

The extension ClassLoader, the first child of the boostrap ClassLoader, is implemented in pure Java code. The extension ClassLoader’s primary responsibility is to load code from the JDK’s extension directories. This in turn provides users of Java the ability to simply drop in or add new code extensions (and hence the name “Extension directory”), such as JNDI , without requiring modification to the user’s CLASSPATH environment variable.

The system, or application, ClassLoader is the ClassLoader returned from the static
method ClassLoader.getSystemClassLoader. This is the ClassLoader responsible for
loading code from the CLASSPATH, and by default will be the parent to any user-created
or user-defined ClassLoader in the system.