Pages

Java ClassLoader

Java ClassLoader is a class found inside the package java.lang. The class loader is responsible for dynamically loading the class for make it available to JVM.

The java.lang.ClassLoader is an abstract class that can be subclassed by applications that need to extend the manner in which the JVM dynamically loads classes.

Every class is loaded by some class loader. The class loader loads the classes from classpath, jre/lib and jre/lib/ext.

Each instance of ClassLoader has an associated parent class loader. The bootstrap class loader does not itself have a parent but may serve as the parent of a ClassLoader instance.


 ClassLoader in Java works on three principle:
  1. Delegation
  2. Visibility
  3. Uniqueness

The Delegation principle forward request of class loading to parent class loader and only loads the class, if parent is not able to find or load class.

Visibility principle allows child class loader to see all the classes loaded by parent ClassLoader, but parent class loader cannot see classes loaded by child.

Uniqueness principle allows to load a class exactly once, which is basically achieved by delegation and ensures that child ClassLoader doesn't reload the class already loaded by parent.

How Class Loader works ?


The loadClass() method of the ClassLoader performs the following tasks, in order, when called to load a class:

If a class has already been loaded, it returns it. Otherwise, it delegates the search for the new class to the parent class loader. If the parent class loader doesn't find the class, loadClass() calls the method findClass() to find and load the class. The findClass() method searches for the class in the current class loader if the class wasn't found by the parent class loader.
Types of class loader
There are three type of class loader used inside JVM
  1. Bootstrap class loader
  2. Extensions class loader
  3. System class loader

Bootstrap class loader


The bootstrap class loader loads the core Java libraries located in the /jre/lib directory. This class loader, which is part of the core JVM, is written in native code.

Extensions class loader


The extensions class loader loads the code in the extensions directories (/jre/lib/ext or any other directory specified by the java.ext.dirs system property.

System class loader


The system class loader loads code found on java.class.path, which maps to the CLASSPATH environment variable.

No comments:

Post a Comment