When a program is launched by the JVM via the main(String args) method, the JVM loads the main Class and then all the classes that are referenced from there on. This is done via the help for. Interestingly there are a variety of classloaders that are created by the JVM, each doing a specialized task.
Types of Class Loaders in JVM
- The Primordial or Bootstrap Classloader is an embedded loader that is created by the JVM first. This classloader is responsible for loading the main class along with other basic run-time classes need to minimally launch the program. This loader loads all the internal classes under the java.* packages. This path is defined by the sun.boot.class.path system property, and typically loads rt.jar and i18n.jar files.
- The Extension Classloader is another one that is created by JVM which loads the classes from the jars files which are in the JDK extension directories. This path is defined by java.ext.dirs system property which is usually defined as lib/ext directory of JRE.
- The System Classloader is another loader that is created by JVM which loads classes from the system classpath. The classes loaded by this loader can be defined using the java.class.path property which is set by the CLASSPATH environment variable.
Class Loader Hierarchy
One of another aspect of the class loaders is that they are hierarchical. They are arranged into a chain with parent child relation.
The class loaders are hierarchical in nature, they use delegation model when loading the class. The classloader request the parent class loader to load the class first before it attempts to load it itself. Once a class is loaded, the child (lower) class in chain, cannot reload the class again. Thus every class is loaded by only one class loader whichever has the visibility.Thus the classes loaded by the child loaders have visibility into the classes loaded by the parent one, but the reverse is not true.
Custom Class loaders
Apart from the 3 basic class loaders, additional class loaders can be created and registered with the JVM run-time. These loaders become siblings to each other and are at the lowest level in the chain of loaders. Being the lowest, these loaders have visibility into all the classes loaded by the parent class loaders ( System, Extension and Bootstrap). This sibling classloaders does not have any visibility into the sibling classloaders expect their parent ones.