Tuesday, November 25, 2008

Understanding Java Classloading and Hierarchy

This article provides the basics of Java Classloading and it makes every successful Java programmer a foundation to understand Classloading behaviour.

Classloaders are fundamental part of the Java Virtual Machine (JVM) that loads classes into memory and is responsible for finding and loading class files at run-time.

Classloader Hierarchy:

Following listing describes on the hierarchy of class loading from top to bottom as parent to child. First three Classloaders together typically shows the Java Classloading hierarchy and with the addition of the fourth Classloader (which has its own hierarchy) shows a typical Enterprise Application Classloader hierarchy.



Things to remember about Classloading:

1. Delegation – Always the current associated Classloader delegates the request to load a class to the immediate parent Classloader before attempting to load on their own. Delegation happens only when a particular class is not loaded in cache already.

2. Visibility - Classes loaded by parent Classloader are visible to all child Classloaders but not vice versa.



3. Uniqueness - Once a class is loaded by any of its parent Classloader, child Classloader in the hierarchy will never reload the class again.

4. Configurable - Most Application Specific Classloaders are configurable based on which the server automatically creates a hierarchy of Classloaders when an application (EAR) is deployed where root shared Classloader is created for loading bean libraries of EJB JAR, independent child Classloader are created for loading classes under the WEB-INF and WEB-INF/lib directories of WAR and for JSP classes for each web application. The parent of the hierarchy created is always System Classpath Classloader. The process of redeploying the application modules without server restart is termed as hot-deployment and is closely related to Classloading.

No comments: