Types of Class loaders in JAVA
Alireza
Posted on November 24, 2024
In Java, there are three primary types of class loaders :
- Bootstrap Class Loader • Function: Loads core Java libraries located in the /lib directory (e.g., rt.jar, resources.jar). • Implemented In: Native code (typically C or C++). • Role: It is the parent of all class loaders and doesn't have a parent itself. It's responsible for loading the fundamental classes required by the JVM.
- Extension (or Platform) Class Loader • Function: Loads classes from the extension directories (/lib/ext or any other directory specified by the java.ext.dirs system property). • Role: It extends the functionality provided by the core Java libraries.
- Application (or System) Class Loader • Function: Loads classes from the classpath, which includes directories and JAR files specified by the CLASSPATH environment variable or -cp command line option. • Role: It is the default class loader used by the JVM to load application-level classes.
/lib
• Location: This is a directory inside your JDK (Java Development Kit) installation. The part represents the root directory where your JDK is installed. For example, if your JDK is installed in C:\Program Files\Java\jdk-14, then /lib would be C:\Program Files\Java\jdk-14\lib.
• Contents: This directory contains essential libraries and resources needed by the Java runtime. It includes core Java classes, such as those found in rt.jar, which is the runtime library.
• Role: The classes in this directory are loaded by the Bootstrap Class Loader, which is the parent class loader in the class loading hierarchy. These are fundamental classes required by the JVM to run Java applications.
/lib/ext
• Location: This is a subdirectory within the lib directory of your JDK installation. For example, if your JDK is installed in C:\Program Files\Java\jdk-14, then /lib/ext would be C:\Program Files\Java\jdk-14\lib\ext.
• Contents: This directory is intended for extensions to the core Java platform. You can place JAR files here that extend the standard Java classes.
• Role: The classes and libraries in this directory are loaded by the Extension Class Loader. It loads additional libraries that are not part of the core Java runtime but are still part of the standard Java platform.
You typically do not need to interact with class loaders directly. However, understanding how they work is useful for debugging or optimizing complex applications.
Here's a quick rundown on when you might need to deal with class loaders in your Java code:
Custom Class Loaders
You might create a custom class loader if you need to load classes in a way that is different from the default behavior. For example, you might need to:
• Load classes from a non-standard location.
• Implement a plugin system where classes are loaded dynamically.
Common Use Cases for Custom Class Loaders
• Dynamic Loading: Loading classes from a network, database, or during runtime from user-provided locations.
• Isolation: Running multiple versions of a library within the same application.
• Plugins: Implementing a plugin architecture where plugins can be loaded/unloaded at runtime without restarting the application.
Practical Tips
• Use Case Specific: Most applications do not need custom class loaders. They are typically used in advanced scenarios.
• Understand Class Loader Hierarchies: Before implementing custom class loaders, ensure you understand the parent-child relationship in class loaders.
Class Loaders
- Bootstrap Class Loader o Function: Loads the core Java libraries from /lib. o Example: Loads classes like java.lang.String, java.util.ArrayList. o Details: Implemented in native code and has no parent.
- Extension (or Platform) Class Loader o Function: Loads classes from /lib/ext or other directories specified by the java.ext.dirs system property. o Example: Loads additional libraries like javax.crypto.Cipher. o Details: Child of the Bootstrap Class Loader.
- Application (or System) Class Loader o Function: Loads classes from the classpath, including directories and JAR files specified by the CLASSPATH environment variable or -cp command line option. o Example: Loads your application classes. o Details: Child of the Extension Class Loader.
Key Points
• Bootstrap Class Loader: Loads core Java classes essential for JVM.
• Extension Class Loader: Loads extension libraries from /lib/ext.
• Application Class Loader: Loads application-specific classes from the classpath.
Core Java classes refer to the fundamental classes that are essential for the basic functionality of the Java programming language and runtime environment. These classes are part of the Java Standard Library and are included in the Java Development Kit (JDK). They are loaded by the Bootstrap Class Loader and are located in the /lib directory.
Key Categories of Core Java Classes
- Java.lang Package: o Includes fundamental classes that are essential to the Java programming language. o Examples: String, Object, Math, System, Thread.
- Java.util Package: o Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and various utility classes. o Examples: ArrayList, HashMap, Collections, Date, Random.
- Java.io Package: o Provides classes for system input and output through data streams, serialization, and the file system. o Examples: File, InputStream, OutputStream, Reader, Writer.
- Java.nio Package: o Offers classes for non-blocking I/O operations, including buffers, charsets, channels, and file systems. o Examples: ByteBuffer, FileChannel, Path, Files.
- Java.net Package: o Contains classes for implementing networking applications. It includes support for both standard networking and secure networking. o Examples: Socket, ServerSocket, URL, HttpURLConnection.
- Javax.security Package: o Includes classes and interfaces for the Java security framework. o Examples: Policy, Principal, Permissions.
- Java.sql Package: o Provides the API for accessing and processing data stored in a data source (usually a relational database) using the Java programming language. o Examples: Connection, Statement, ResultSet, PreparedStatement.
- Javax.xml Package: o Contains classes for parsing XML documents using different APIs like DOM, SAX, and StAX. o Examples: DocumentBuilder, SAXParser, XMLStreamReader.
Why Core Java Classes Are Important
• Foundation: These classes form the foundation upon which all Java applications are built. Without them, the Java runtime environment cannot function.
• Predefined Functionality: They provide predefined functionality that developers can use to build applications, making development faster and easier.
• Standardization: Core classes ensure standardization across Java applications, promoting portability and compatibility.
rt.jar stands for runtime JAR file. It's a critical component of the Java Runtime Environment (JRE) and contains all the core class libraries used by the Java Virtual Machine (JVM) to run Java applications.
Key Points About rt.jar
- Location: o It is typically found in the /lib directory of your JDK or JRE installation. For example, if your JDK is installed in C:\Program Files\Java\jdk-14, rt.jar would be located at C:\Program Files\Java\jdk-14\lib\rt.jar.
- Contents: o rt.jar includes all the standard classes from the Java Standard Library, which are essential for the Java runtime. This includes fundamental packages such as java.lang, java.util, java.io, and others.
- Role: o It provides the JVM with the core libraries required to execute Java programs. When a Java application runs, the JVM loads classes from rt.jar to ensure that essential functionalities are available.
- Class Loader: o The Bootstrap Class Loader is responsible for loading classes from rt.jar. This is the parent class loader in the Java class loading mechanism and ensures that core classes are loaded first and are always available. Importance of rt.jar • Centralized Class Repository: It centralizes all core classes in a single archive, making it easy for the JVM to access them quickly. • Standardization: Ensures that every Java application has access to the same core libraries, promoting consistency and compatibility across different Java environments. • Performance: Loading classes from a single JAR file can improve performance compared to loading classes from multiple directories. Deprecation Note With the release of Java 9 and later versions, the traditional rt.jar file has been replaced by the Java Platform Module System (JPMS), also known as Project Jigsaw. This new system modularizes the Java runtime, making it more scalable and maintainable. In these versions, core classes are divided into modules rather than being bundled in a single rt.jar file. If you’re using Java 9 or later, you won’t find rt.jar, and instead, you’ll encounter the module system that provides a more granular way of organizing and loading Java classes.
Class loaders play a crucial role in the execution of a Java application, but not all class loaders are actively "running" as applications might typically do. Instead, they are part of the underlying mechanism that loads classes into memory for execution by the Java Virtual Machine (JVM).
How Class Loaders Work
- Bootstrap Class Loader: o This is the initial class loader responsible for loading core Java classes located in /lib. It is implemented in native code. o Since it is the parent of all class loaders, it handles the essential classes needed by the JVM to run any Java application.
- Extension Class Loader: o This loader is responsible for loading classes from the extension directories (/lib/ext). o It is a child of the Bootstrap Class Loader and provides additional functionality beyond the core Java classes.
- Application (System) Class Loader: o This loader loads classes from the user-defined classpath, which includes directories and JAR files specified by the CLASSPATH environment variable or the -cp command-line option. o It is the default class loader used to load application-specific classes. Class Loader Hierarchy • Delegation Model: Class loaders follow a parent-delegation model. When a class loader is asked to load a class, it first delegates the request to its parent class loader. Only if the parent class loader cannot find the class does the child class loader attempt to load it. • Lifecycle: While the class loaders themselves aren't "running" in the sense of an application, they are constantly invoked by the JVM as needed during the execution of a Java program.
Example Scenario
When you run a Java application, here's how class loading typically happens:
- The Bootstrap Class Loader loads the core classes like java.lang.Object, java.util.HashMap, etc.
- If your application uses any extension libraries (like some cryptographic libraries), the Extension Class Loader loads those classes.
- Finally, the Application Class Loader loads the classes that are part of your application, including custom classes and third-party libraries added to your classpath. This hierarchical and delegative loading process ensures that classes are efficiently and consistently loaded into memory, maintaining the application's runtime environment.
The Application Class Loader (also known as the System Class Loader) is primarily responsible for loading your code and classes in a typical Java application. Here’s how it works in more detail:
Role of the Application Class Loader :
- Loading Application Classes: The Application Class Loader loads classes from the classpath, which includes directories and JAR files specified by the CLASSPATH environment variable or the -cp command-line option. o Example: When you compile your Java code into bytecode (.class files) and place them in a directory or package structure, the Application Class Loader will load these classes when your application runs.
- Third-Party Libraries: It also loads any third-party libraries that you include in your project’s classpath. o Example: If you’re using a library like Apache Commons, the Application Class Loader will load these classes from the JAR files included in your classpath. Class Loading Process • When you run a Java application using a command like java MyClass, the JVM initiates the class loading process. Here’s a simplified flow:
- Bootstrap Class Loader: Loads the essential Java runtime classes (e.g., java.lang.Object).
- Extension Class Loader: Loads classes from the extension directory (/lib/ext).
- Application Class Loader: Finally, it loads your application classes and any third-party libraries from the specified classpath.
Class Loading Process
- Bootstrap Class Loader: Loads core classes necessary for the JVM's operation from the lib directory.
- Extension Class Loader: Loads classes from the lib/ext directory or specified directories.
- Application Class Loader: Loads classes from the application's classpath.
Java Platform Module System (JPMS)
In Java 9 and later versions, the traditional rt.jar file was replaced by the Java Platform Module System (JPMS), also known as Project Jigsaw. Here's a detailed explanation of what happened and how the class loading process works in the modular system:
Introduction in Java 9:
o Java 9 introduced the module system to improve the scalability and maintainability of the JDK.
o The monolithic rt.jar file, which contained all the core Java classes, was broken down into smaller, well-defined modules.Modular JDK:
o The JDK is now organized into modules, each with a specific purpose and set of classes.
o For example, java.base is the foundational module that contains essential classes like java.lang, java.util, and java.io.Module Path:
o Instead of the classpath, Java 9+ uses the module path to locate modules.
o The module path specifies the location of module JARs or directories containing module descriptors (module-info.class).Module Descriptor:
o Each module has a module-info.java file that declares the module name and its dependencies.
Class Loading in the Modular System :
- Module Layers: o The module system uses layers to manage the visibility and loading of modules. o Each module layer can define its own class loader hierarchy.
- Class Loader for Modules: o The Boot Layer is the primary layer containing system modules loaded by the Bootstrap class loader. o User-Defined Layers can be created for custom modules and applications. Practical Changes • No rt.jar: Instead of a single runtime JAR file, the core classes are now distributed across multiple modules. • Improved Performance: The modular system allows for more efficient class loading and smaller application footprints. • Enhanced Security: Modules can define explicit dependencies, reducing the risk of classpath issues and improving encapsulation.
The shift from rt.jar to the module system in Java 9+ represents a significant advancement in how Java manages class loading and dependencies. This modular approach offers improved performance, scalability, and security, making it a robust solution for modern Java application
Posted on November 24, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.