Sub topic 10
Parent delegation
This chapter assumes you can run javac and java, know what a class and a static member are, and have read the previous chapter on the bootstrap, platform and application class loaders. Here you will see how those loaders cooperate when a class is requested, why the JVM works this way, and where the rule breaks down.
The rule in one sentence
When a class loader is asked to load a class, it first asks its parent. It tries to load the class itself only if the parent cannot find it.
This is called parent delegation. The request travels up the chain until it reaches the bootstrap loader. Each loader on the way back down gets one chance to find the class.
The path of a request
In Java 11 the default chain is: application loader, then platform loader, then bootstrap loader. The bootstrap loader is built into the JVM, and getParent() reports it as null.
For java.lang.String the chain ends early. The bootstrap loader finds it, and neither lower loader searches its own path.
What loadClass does
The default ClassLoader.loadClass(String, boolean) implements delegation. Its logic, simplified, is:
- Call
findLoadedClass(name). If this loader already loaded the class, return it. - If there is a parent, call
parent.loadClass(name). If there is no parent, ask the bootstrap loader. - If the parent threw
ClassNotFoundException, catch it and callfindClass(name)on this loader. - Optionally resolve the class, then return it.
The first step makes loading idempotent. Asking the same loader for the same name twice returns the same Class object.
You can observe the result with the demo from the previous chapter:
public class LoaderDemo {
public static void main(String[] args) {
System.out.println(String.class.getClassLoader());
System.out.println(ClassLoader.getPlatformClassLoader());
ClassLoader app = LoaderDemo.class.getClassLoader();
System.out.println(app);
System.out.println(app.getParent());
}
}The first line prints null because String came from the bootstrap loader. The last line prints the platform loader, which is the parent of the application loader.
Watching delegation happen
Unified logging shows every class as it loads and where it came from:
$ java -Xlog:class+load:file=classload.log LoaderDemoOpen classload.log. Entries for JDK classes show a source such as shared objects file or jrt:/java.base. Your own class shows a file: source. The loader that defined a class is not always the one that was first asked, which is the point of delegation.
Why the JVM delegates
There are three practical reasons.
- Core class safety. Application code cannot supply its own
java.lang.Objectorjava.lang.String. The request always reaches the bootstrap loader first, and it finds the real one. - No duplicates. A class shared by many loaders is loaded once, high in the chain, and everyone sees the same
Classobject. - Consistent types. Classes from different layers can refer to each other by name and mean the same type.
Customizing safely: findClass, not loadClass
Because loadClass implements delegation, the recommended way to write a custom loader is to override findClass. The default loadClass asks the parent first and calls your findClass only on failure.
public class BytesClassLoader extends ClassLoader {
private final String className;
private final byte[] classBytes;
public BytesClassLoader(ClassLoader parent, String className, byte[] classBytes) {
super(parent);
this.className = className;
this.classBytes = classBytes;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
if (!name.equals(className)) {
throw new ClassNotFoundException(name);
}
return defineClass(name, classBytes, 0, classBytes.length);
}
}The parent argument sets the delegation target. Passing null makes the bootstrap loader the parent, which means platform and application classes become invisible to your loader.
A subtle consequence: the parent wins
Suppose Foo exists on the application class path and also in the bytes your custom loader holds. If your loader's parent is the application loader, loadClass("Foo") returns the parent's version. Your findClass never runs.
This surprises people who expect a custom loader to "override" a class. To get your version you must do one of the following:
- Give the loader a parent that cannot see
Foo. - Override
loadClassand check your own source before delegating.
The second option is how some application servers and plugin systems work. It trades safety for isolation, so apply it only to your own packages and still delegate for java.*.
Visibility runs in one direction
Delegation creates a one-way view. A child can see everything its parent loaded. A parent cannot see what its children loaded.
Consider a library on the application class path that calls Class.forName("com.plugin.Impl"). That call uses the library's own loader, the application loader. If Impl was defined by a custom plugin loader that is a child, the lookup fails with ClassNotFoundException.
Frameworks work around this in several ways:
- Thread context class loader.
Thread.currentThread().getContextClassLoader()lets code at a higher level use a loader supplied by the caller. Service-lookup APIs such asServiceLoader.load(Class)use it by default. - Passing a loader explicitly.
Class.forName(name, true, loader)names the loader to use. - Interfaces from the parent. The plugin implements an interface that the parent loaded, and the host calls it through that interface.
Which loader defines the class
Two loaders are involved in any load. The initiating loader is the one the code asked. The defining loader is the one whose defineClass produced the Class. With delegation they often differ: the application loader initiates a request for String, and the bootstrap loader defines it.
The JVM records both. The runtime identity of a class is the pair of its name and its defining loader. That is why two loaders that each call defineClass on the same bytes get two incompatible classes. The next chapters return to this.
Common errors
| Symptom | Likely cause |
|---|---|
| `ClassNotFoundException` from `Class.forName` | The calling class's loader and its ancestors cannot see the class. It may live in a child or sibling loader. |
| Your custom version of a class is ignored | The parent found its own version first, so `findClass` was never called. |
| `SecurityException: Prohibited package name: java.…` | `defineClass` was called with a name in the `java.` package. |
| Class not found only when your loader has `null` as parent | The bootstrap-only parent hides platform and application classes. |
| Works in one container, fails in another | Different loader hierarchies, so a class is visible in one and not the other. |
Concurrency: parallel-capable loaders
A loader that is parallel capable can load different class names on different threads at once. The default loadClass locks per class name through getClassLoadingLock(name) rather than locking the whole loader. A custom loader that registers itself as parallel capable must call ClassLoader.registerAsParallelCapable() in a static initializer. Loaders that do not do this lock on the loader object itself, which is safe but slower. Cycles of loaders that delegate to each other with coarse locks can deadlock, so keep the parent graph acyclic.
Putting it together
A short experiment confirms the one-way view. This program defines a child loader whose parent is the application loader, then asks the parent for a class only the child knows:
public class VisibilityDemo {
public static void main(String[] args) throws Exception {
ClassLoader app = VisibilityDemo.class.getClassLoader();
byte[] bytes = new byte[0];
BytesClassLoader child = new BytesClassLoader(app, "Hidden", bytes);
try {
app.loadClass("Hidden");
} catch (ClassNotFoundException e) {
System.out.println("parent cannot see: " + e.getMessage());
}
System.out.println("child delegates upward: "
+ (child.loadClass("java.lang.String") == String.class));
}
}Compile it together with BytesClassLoader. The first loadClass fails because the parent has no Hidden class on its path. The second prints true: the child asked its parent, the chain reached the bootstrap loader, and the same String class came back.
Exercise
You write a custom loader with the application loader as its parent and override only findClass to return your own version of com.example.Config, which also exists on the class path. Which version does loadClass("com.example.Config") return, and what are two ways to make your version win?
Show answer
It returns the class-path version. loadClass asks the parent first, the parent finds com.example.Config, and findClass is never called. To make yours win, either give the loader a parent that cannot see com.example.Config (for example the platform loader), or override loadClass to check your own source before delegating, while still delegating java.* names.
Exercise
A library loaded by the application loader calls Class.forName("com.plugin.Impl"), but Impl was defined by a child plugin loader. Why does the call throw ClassNotFoundException, and how can the library find the class?
Show answer
Class.forName uses the caller's defining loader, the application loader. Delegation only looks upward, so the application loader cannot see classes defined by its child. The library can use the thread context class loader, call Class.forName(name, true, pluginLoader) with an explicit loader, or have the plugin implement an interface loaded by the parent and be reached through ServiceLoader.