Tuesday, 27 November 2012

Why do you need a Custom Classloader?

Java Runtime loads the classes dynamically at runtime using class loaders. By default a JVM will consists of these three class loaders:

BootStrap Class loader This is the classloader which is loads all the core classes required by the JVM. They are basically the Java classes from the packages like java.lang.*, java.io.*, java.util.* etc. One can append additional class locations to this class loader using -Xbootclasspath/p: and -Xbootclasspath/a: JVM options.

Extension Class loader It is the classloader which is an alternative to the BootStrap class loader. One can drop the additional classes packaged in JAR file in /lib/ext folder to get it picked by JVM.

System Class loader It is the classloader which loads the classes specified in the CLASSPATH. It is also called as application classloader.

JVM allows you to create custom class loader which can address several problems. They are mostly useful in larger
architectures consisting of several module/applications. Here are the
advantages of the custom class loader:

Modular architecture They allow you to define multiple class loader allowing modular architecture. Each module can have their own classloader.

Isolation Clearly defines the scope of the class to within the class loader. It avoid conflicts if a class is present in two modules.

Support Versioning Supports different versions of class within same VM for different modules.

Memory Management Classes can be loaded and unloaded whenever required.

Load classes from anywhere Classes can be loaded from anywhere, for ex, Database, Networks, or even define it on the fly.

Add resources or classes dynamically All the above features allows you add classes or resources dynamically.

Runtime Reloading Modified Classes Allows you to
reload a class or classes at runtime by creating a child class loader to
the actual class loader, which contains the modified classes.

A good example of Custom class loader is JavaEE Application Server. Where each Web or Enterprise application will be class loader by itself.