Classloader in Java

The class loader is the part of the JRE that dynamically loads Java classes into the JVM. Classes are usually only loaded upon request. The Java runtime doesn't need to know about files and file systems thanks to the class loader. Delegation is an important concept that the loader does. The class loader is responsible for finding libraries, reading their contents, and loading the classes contained in the libraries. This loading is usually done "on demand" because it does not happen until the program calls the class. A named class can only be loaded once by a given classloader.

When the JVM starts up, three classloaders are used:

  • Bootstrap class loader
  • Extensions class loader
  • System class loader

The Bootstrap class loader loads the core Java libraries located in the <JAVA_HOME>/jre/lib folder. This loader is part of the core JVM, written in native code.

The extension class loader loads the code into the extension directories (<JAVA_HOME>/jre/lib/ext, or any other directory specified by the java.ext.dirs system property).

The system class loader loads the code found in java.class.path, which maps to the CLASSPATH environment variable. This is implemented by the sun.misc.Launcher$AppClassLoader class.

The class loader does three main things in strict order:

  • Load: Finds and imports binary data for a type.
  • Binding: Performs validation, preparation, and (optional) permission.
    • Validation: Ensures that the imported type is correct.
    • Preparation: Allocates memory for class variables and initializes memory to default values.
    • Resolution: Converts symbolic links from type to direct links.
  • Initialization: Calls Java code that initializes class variables with their correct initial values.

Custom class loader

The class loader is written in Java. Therefore it is possible to create your own classloader without understanding the fine details of the JVM. Each Java classloader has a parent classloader that is defined when a new classloader is instantiated or as the default system classloader for a virtual machine.

What makes the following possible:

  • load or unload classes at runtime (for example, dynamically load libraries at runtime, even from an HTTP resource). This is an important feature for:
    • implementation of scripting languages;
    • using bean builders;
    • add a custom extension;
    • allowing multiple namespaces to communicate. For example, it is one of the foundations of the CORBA / RMI protocols;
  • change how the bytecode is loaded (for example, you can use the encrypted Java class bytecode);
  • modify the loaded bytecode (for example, for weaving aspects at boot time using aspect-oriented programming);

Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed