Parent delegation
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)When a class loader is asked for a class, it does not search its own place first. It asks its parent first, all the way up to the bootstrap loader, and searches itself only if no parent can find the class.
A loader asks its parent first before loading a class itself
Parent delegation is the rule that a class loader first asks its parent to load a class and loads it itself only if the parent cannot.
Parent delegation is the rule every built-in loader follows when loadClass(name) is called: hand the request to the parent first, and look for the class yourself only if the parent fails.
- Check whether this loader has already loaded the class. If yes, return the same
Classobject. - Ask the parent loader to load it. The parent repeats these steps with its own parent.
- At the top, the bootstrap loader looks among the core classes.
- If no parent found the class, call this loader's own
findClass(name). - If
findClassfails too, throwClassNotFoundExceptionback to whoever asked (often the child, which then tries its ownfindClass).
Example 1 · Logging every step of delegation
class LoggingLoader extends ClassLoader { LoggingLoader(String name, ClassLoader parent) { super(name, parent); }
@Override protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException { System.out.println(getName() + ": loadClass(" + className + ")"); return super.loadClass(className, resolve); // the normal delegation }
@Override protected Class<?> findClass(String className) throws ClassNotFoundException { System.out.println(getName() + ": findClass(" + className + ") - not found here"); throw new ClassNotFoundException(className); }}
class Marksheet {}
public class DelegationDemo { static String loaderName(Class<?> c) { ClassLoader l = c.getClassLoader(); return l == null ? "bootstrap" : l.getName(); }
public static void main(String[] args) { ClassLoader app = DelegationDemo.class.getClassLoader(); LoggingLoader college = new LoggingLoader("college", app); LoggingLoader dept = new LoggingLoader("dept", college);
String[] names = {"java.lang.String", "Marksheet", "Hallticket"}; for (String n : names) { System.out.println("Asking dept for " + n); try { Class<?> c = dept.loadClass(n); System.out.println(" -> loaded by " + loaderName(c)); } catch (ClassNotFoundException e) { System.out.println(" -> ClassNotFoundException: " + e.getMessage()); } } }}Asking dept for java.lang.String dept: loadClass(java.lang.String) college: loadClass(java.lang.String) -> loaded by bootstrap Asking dept for Marksheet dept: loadClass(Marksheet) college: loadClass(Marksheet) -> loaded by app Asking dept for Hallticket dept: loadClass(Hallticket) college: loadClass(Hallticket) college: findClass(Hallticket) - not found here dept: findClass(Hallticket) - not found here -> ClassNotFoundException: Hallticket
What this code does
- The chain is dept → college → app → platform → bootstrap. Each request climbs it:
Stringis found at the top by bootstrap,Marksheetbyapp, and neither custom loader'sfindClassruns. Hallticketexists nowhere. Every parent fails, so thefindClasscalls run on the way back down:collegefirst, thendept, and finallyClassNotFoundExceptionreachesmain.
The parent does the same with its own parent, so a request climbs the chain up to the bootstrap loader.
Why delegation keeps core classes safe and unique
Because every request reaches the bootstrap loader first, a core class such as java.lang.String is always the one from the JDK. A String class sitting on your class path is never even looked at.
Example 2 · Trying to replace java.lang.String
# java/lang/String.java contains: package java.lang; public class String { main(...) }javac java/lang/String.java# compile it in the old Java 8 mode, then try to run itjavac --release 8 -d out java/lang/String.javajava -cp out java.lang.Stringjava\lang\String.java:1: error: package exists in another module: java.base package java.lang; ^ 1 error ... Error: Main method not found in class java.lang.String, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
What this code does
- A real run with JDK 21 on Windows, trimmed (the
--release 8step prints only warnings about the old release). On Java 9 and later, javac itself refuses: the packagejava.langbelongs to thejava.basemodule. - Even with the class compiled,
javaasks the application loader, which delegates up to bootstrap. Bootstrap finds the realString, which has nomain. The fakeout/java/lang/String.classis never loaded.
Example 3 · A custom loader cannot define a java.* class
class RogueLoader extends ClassLoader { RogueLoader() { super("rogue", ClassLoader.getSystemClassLoader()); }
Class<?> tryToDefine(String name, byte[] bytes) { return defineClass(name, bytes, 0, bytes.length); }}
public class ProtectedPackageDemo { public static void main(String[] args) throws Exception { RogueLoader rogue = new RogueLoader();
Class<?> s = rogue.loadClass("java.lang.String"); System.out.println("Asked rogue for java.lang.String, defining loader: " + s.getClassLoader()); System.out.println("Same String class as everyone else: " + (s == String.class));
try { rogue.tryToDefine("java.lang.FakeString", new byte[0]); } catch (SecurityException e) { System.out.println("SecurityException: " + e.getMessage()); } }}Asked rogue for java.lang.String, defining loader: null Same String class as everyone else: true SecurityException: Prohibited package name: java.lang
What this code does
- Asking
rogueforStringgoes up the chain and returns the bootstrap'sString, the sameClassobject every other class uses. defineClasschecks the name before it even reads the bytes: anyjava.*name from a non-platform loader is refused withSecurityException.
This gives two guarantees. Safety: no library or downloaded code can swap in its own String, Object or SecurityManager. Uniqueness: there is exactly one String class in the JVM, so a String from one library can be passed to any other library. A second wall protects the core packages: ClassLoader.defineClass refuses any class name in a java.* package unless it is the platform loader, and on Java 9 and later javac refuses to compile a class into a package that the JDK's modules already own.
loadClass versus findClass
loadClass(name) is the public entry point: it checks the cache, delegates to the parent and, only if that fails, calls findClass(name). findClass is the protected method that looks in this loader's own place: a folder, a JAR, a database or the network.
Example 4 · findClass runs only when the parents fail
import java.io.IOException;import java.io.InputStream;
class Notice { public String toString() { return "Exam timetable is out"; }}
class FolderLoader extends ClassLoader { FolderLoader(String name, ClassLoader parent) { super(name, parent); }
@Override protected Class<?> findClass(String className) throws ClassNotFoundException { System.out.println(" " + getName() + ".findClass(" + className + ")"); String file = className.replace('.', '/') + ".class"; // For this demo the bytes come from the class path; a real loader // would read them from its own folder, JAR, database or network. try (InputStream in = ClassLoader.getSystemResourceAsStream(file)) { if (in == null) { throw new ClassNotFoundException(className); } byte[] bytes = in.readAllBytes(); return defineClass(className, bytes, 0, bytes.length); } catch (IOException e) { throw new ClassNotFoundException(className, e); } }}
public class FindClassDemo { public static void main(String[] args) throws Exception { // parent = platform, so the parent cannot see the class path FolderLoader loader = new FolderLoader("notices", ClassLoader.getPlatformClassLoader());
System.out.println("loadClass(java.lang.String):"); Class<?> s = loader.loadClass("java.lang.String"); System.out.println(" defined by: " + (s.getClassLoader() == null ? "bootstrap" : s.getClassLoader().getName()));
System.out.println("loadClass(Notice):"); Class<?> n = loader.loadClass("Notice"); System.out.println(" defined by: " + n.getClassLoader().getName());
System.out.println("loadClass(Notice) again:"); Class<?> again = loader.loadClass("Notice"); System.out.println(" same Class object: " + (again == n)); System.out.println("Same as the app's Notice.class: " + (n == Notice.class)); }}loadClass(java.lang.String): defined by: bootstrap loadClass(Notice): notices.findClass(Notice) defined by: notices loadClass(Notice) again: same Class object: true Same as the app's Notice.class: false
What this code does
FolderLoaderoverrides onlyfindClass. ForStringthe parent chain succeeds, sofindClassis never called. ForNoticethe platform parent fails, sofindClassreads the bytes and callsdefineClass.- The second request is answered from the loader's cache, with no
findClasscall. And theNoticedefined bynoticesis a different class from the app'sNotice: same name, different loader.
To write a custom loader, override findClass and leave loadClass alone. You keep delegation for free, and you only write the part that is really yours: get the bytes, then call defineClass(name, bytes, 0, length) to turn them into a Class. Overriding loadClass changes the delegation order itself. Some servers do this on purpose ("child-first" loading, described in the interview tab), but most code should not.
What happens when the same class is on the class path twice
The application loader searches the class path in order, entry by entry, and takes the first match. If FeeRules.class is in both v1 and v2, the one in the entry listed first wins, and the other copy is silently ignored.
Example 5 · The same class in two folders: the first one wins
# v1/FeeRules.class says "fee rules v1 (hostel Rs 40000)"# v2/FeeRules.class says "fee rules v2 (hostel Rs 45000)"java -cp "app;v1;v2" FeeAppjava -cp "app;v2;v1" FeeAppjava -Xlog:class+load -cp "app;v2;v1" FeeApp | findstr FeeRulesUsing fee rules v1 (hostel Rs 40000) Using fee rules v2 (hostel Rs 45000) [0.105s][info][class,load] FeeRules source: file:/C:/.../twice/v2/
What this code does
- A real run on Windows with JDK 21 (on macOS write
app:v1:v2and usegrep). The same command with the folders swapped gives a different hostel fee, and Java prints no warning at all. - The load log names the folder the class really came from. When two versions of a library are on the class path, this line tells you which one is running.
There is no warning and no error.
This is a classic source of "it works on my machine" bugs, sometimes called JAR hell: two versions of the same library end up on the class path, and the order decides which one runs. -Xlog:class+load shows the source of each class, so you can see which copy was used.
; on Windows and : on macOS and Linux.Next step
Check your understanding
11 quick questions