Java Class Loading Mechanism

4 minute read

Before a Java class can be used, the JVM must find it, load it, verify it, and initialize it. This entire process is handled by class loaders — and understanding them is essential for debugging ClassNotFoundException, NoClassDefFoundError, and classloader leaks.


The Three Built-in Class Loaders

┌─────────────────────────────────────┐
│     Bootstrap Class Loader          │  ← java.lang, java.util (JDK core)
│     (Native C/C++, not a Java obj) │
└──────────────┬──────────────────────┘
               │ parent
┌──────────────▼──────────────────────┐
│     Platform Class Loader           │  ← javax.*, java.sql, java.xml
│     (formerly Extension)            │
└──────────────┬──────────────────────┘
               │ parent
┌──────────────▼──────────────────────┐
│     Application Class Loader        │  ← Your app classes + classpath JARs
│     (System Class Loader)           │
└─────────────────────────────────────┘
Loader Loads Location
Bootstrap java.lang.*, java.util.*, core JDK $JAVA_HOME/lib
Platform javax.*, java.sql.*, platform modules $JAVA_HOME/lib (modules)
Application Your classes, classpath JARs -cp / CLASSPATH

Parent Delegation Model

When a class is requested, the loader delegates to its parent first:

Request: load com.example.MyService

Application Loader → "Do I have it cached?" → No
  └─► Platform Loader → "Do I have it cached?" → No
        └─► Bootstrap Loader → "Do I have it cached?" → No
              └─► "Can I load it?" → No (not a JDK class)
        └─► "Can I load it?" → No (not a platform class)
  └─► "Can I load it?" → YES → Load from classpath

Why delegation?

  1. Security — prevents replacing java.lang.String with a malicious version
  2. Uniqueness — each class is loaded once by the same loader
  3. Consistency — JDK classes always come from the bootstrap loader

Class Loading Phases

A class goes through three phases:

1. Loading

The class loader finds the .class file (from disk, network, or generated) and reads the bytecode into memory.

// Trigger loading explicitly
Class<?> clazz = Class.forName("com.example.MyService");

// Or implicitly
MyService service = new MyService();  // triggers load if not loaded

2. Linking

Sub-phase What Happens
Verification Bytecode verified for correctness (no stack overflow tricks, valid types)
Preparation Static fields allocated and set to default values (0, null, false)
Resolution Symbolic references (class names in constant pool) resolved to direct references

3. Initialization

Static initializers and static {} blocks execute — in order of appearance:

public class Config {
    static final String ENV = System.getenv("APP_ENV");  // runs during init

    static {
        System.out.println("Config initialized");        // runs during init
    }
}

Key: A class is initialized only once, the first time it’s actively used (instantiation, static method call, or static field access).


Custom Class Loaders

Sometimes you need to load classes from non-standard locations:

public class PluginClassLoader extends ClassLoader {

    private final Path pluginDir;

    public PluginClassLoader(Path pluginDir, ClassLoader parent) {
        super(parent);
        this.pluginDir = pluginDir;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            String fileName = name.replace('.', '/') + ".class";
            Path classFile = pluginDir.resolve(fileName);
            byte[] bytes = Files.readAllBytes(classFile);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            throw new ClassNotFoundException(name, e);
        }
    }
}
// Usage
ClassLoader pluginLoader = new PluginClassLoader(Path.of("/plugins"), getClass().getClassLoader());
Class<?> pluginClass = pluginLoader.loadClass("com.plugin.MyPlugin");
Object plugin = pluginClass.getDeclaredConstructor().newInstance();

Use cases: plugin systems (like Tomcat loading WARs), hot reloading, isolation.


Common Errors

Error Cause Fix
ClassNotFoundException Class not found on classpath at runtime Check classpath, missing JAR
NoClassDefFoundError Class was found at compile time but not at runtime Missing dependency, packaging issue
LinkageError Same class loaded by two different class loaders Classloader isolation issue
ExceptionInInitializerError Static initializer threw an exception Fix the static {} block

Key Difference: ClassNotFoundException vs NoClassDefFoundError

// ClassNotFoundException — explicit load fails
try {
    Class.forName("com.missing.MyClass");  // throws ClassNotFoundException
} catch (ClassNotFoundException e) { }

// NoClassDefFoundError — class existed at compile time, missing at runtime
// You compiled with library-1.0.jar, but deployed without it
MyLibraryClass obj = new MyLibraryClass();  // throws NoClassDefFoundError

Module System Impact (Java 9+)

The Java Platform Module System (JPMS) changed class loading:

module com.myapp {
    requires java.sql;          // explicit dependency
    exports com.myapp.api;      // visible to other modules
}
Before Java 9 After Java 9
Everything on classpath Modules with explicit dependencies
No encapsulation exports controls visibility
Extension classloader Platform classloader
JAR hell common Module system prevents conflicts

Class Unloading

Classes can be garbage collected when:

  1. No instances of the class exist
  2. The Class object is unreachable
  3. The class loader that loaded it is unreachable
// This is why classloader leaks happen in app servers:
// Redeploy creates new classloader, but old one is retained
// because something (ThreadLocal, static reference) holds a reference

Common Mistakes

Mistake Problem Fix
Using Thread.currentThread().getContextClassLoader() without understanding it Returns unexpected loader in complex setups Know when to use context vs class loader
Static collections holding class references Prevents class/loader GC → memory leak Use weak references or clear on undeploy
Not closing classloaders URLClassLoader holds file handles open Call close() in try-with-resources

Key Takeaways

  1. Three loaders: Bootstrap → Platform → Application, with parent delegation.
  2. Loading phases: Load → Link (verify, prepare, resolve) → Initialize.
  3. Classes initialize once, on first active use.
  4. ClassNotFoundException = not on classpath. NoClassDefFoundError = was there at compile time, gone at runtime.
  5. Custom class loaders enable plugins, isolation, and hot reloading.
  6. Java 9+ modules add explicit dependency declarations.

What’s Next?

Next: Heap, Stack, and Method Area — where your objects, variables, and class metadata actually live in memory.

Updated: