☕ Java Q53 / 162

What are different class loaders in Java?

AI-Powered Answer ✓ Answered

Class loaders in Java are essential components of the Java Virtual Machine (JVM) responsible for dynamically loading Java classes into memory during runtime. They follow a hierarchical delegation model to ensure security and efficient class management. When a class needs to be loaded, the request is typically delegated to its parent class loader first.

Core Class Loaders in Java

1. Bootstrap Class Loader (Primordial Class Loader)

This is the highest-level class loader and is not implemented in Java; it's part of the JVM's native code (e.g., C/C++). It is responsible for loading the core Java API classes (like java.lang.*, java.util.*) from the rt.jar (or jimage in modular Java versions) and other essential runtime classes located in the <JAVA_HOME>/jre/lib directory. It has no parent class loader.

2. Extension Class Loader (Platform Class Loader in Java 9+)

This class loader is a child of the Bootstrap Class Loader. Its primary role is to load classes from the JAR files located in the <JAVA_HOME>/jre/lib/ext directory, or any other directories specified by the java.ext.dirs system property. These typically contain standard extensions to the Java platform.

3. Application Class Loader (System Class Loader)

This is the most commonly used class loader for loading application-specific classes. It is a child of the Extension Class Loader. It loads classes from the classpath, which can be defined by the -classpath or -cp command-line options, or the java.class.path system property. When you run a Java application, this class loader loads your own classes and third-party libraries.

Custom Class Loaders

Developers can extend the java.lang.ClassLoader class to create custom class loaders. These are often used for specialized scenarios such as:

  • Loading classes from non-standard locations (e.g., network, database, encrypted files).
  • Implementing hot deployment of applications without restarting the JVM.
  • Providing isolated environments for different applications within the same JVM (e.g., in application servers like Tomcat or JBoss).
  • Enhancing security by applying custom loading policies.

The Delegation Model

The Java class loading mechanism operates on a delegation model. When a class loader is asked to load a class, it first delegates the request to its parent class loader. This process continues up the hierarchy until the Bootstrap Class Loader is reached. If a parent class loader successfully loads the class, that class is returned. Only if no parent class loader can find or load the class, the original class loader attempts to load it itself. This model ensures that core API classes are always loaded by trusted class loaders and prevents potential security vulnerabilities where malicious code might try to replace standard Java classes.