classloaders: Java class loaders module (three built-in loaders and which modules each owns, parent delegation traced across a two-loader chain, child-first PluginLoader, class identity and the failing (Plugin) cast, Class.forName vs loadClass initialisation, ClassNotFoundException vs NoClassDefFoundError incl. 'Could not initialize class', hot reload, unloading and a Registry leak, context class loader, jcmd VM.classloaders), 18 contract tests

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b5pUjAyJuUaNEQqzGJ
This commit is contained in:
Ankur
2026-11-25 13:17:24 +05:30
co-authored by Claude Sonnet 5.5
parent 74da9cd899
commit cca173d104
37 changed files with 1151 additions and 0 deletions
+1
View File
@@ -37,6 +37,7 @@ article; each module's own README has that article's version table, quickstart,
| [`random`](random/) | Random vs ThreadLocalRandom vs SecureRandom vs RandomGenerator in Java |
| [`completablefuture`](completablefuture/) | CompletableFuture in Java: thenApply vs thenCompose, allOf, Exceptions and Timeouts (and When Virtual Threads Win) |
| [`streams`](streams/) | Java Stream API Tutorial with Examples + Collectors Cookbook (laziness, collectors, primitive and parallel streams, Gatherers) |
| [`classloaders`](classloaders/) | Java ClassLoaders Explained: Delegation, Custom Loaders, ClassNotFoundException vs NoClassDefFoundError |
## License
+44
View File
@@ -0,0 +1,44 @@
# classloaders
Companion code for the ankurm.com post *"Java ClassLoaders Explained: Delegation, Custom Loaders, ClassNotFoundException vs NoClassDefFoundError."*
Module in `java-core-examples`, the Java-core series. All explanation lives in the post; this module holds the code and the captured output.
## Versions this was built and tested against
| Component | Version | Notes |
|---|---|---|
| JDK | 25.0.5.1 (Temurin, LTS) | Named loaders and `getName()` arrived in JDK 9; `jcmd VM.classloaders` in JDK 11. |
| JUnit Jupiter | 5.11.0 | |
| Maven | 3.9.11 | |
## Quickstart
```bash
export JAVA_HOME=/path/to/jdk-25
mvn compile
scripts/run.sh HierarchyDemo # one demo
scripts/run-all.sh # regenerate every file in output/
```
The demos compile the little plugin sources under `plugins/` at run time with `javax.tools`, so the
module needs a JDK (not a JRE) and must be run from the module directory.
## What's in here
| File | What it shows | Output |
|---|---|---|
| `HierarchyDemo.java` | Which loader defined `String`, `java.sql.Driver`, your class and an array; the parent chain; modules per loader. | `output/01` |
| `DelegationDemo.java` + `DirLoader.java` | Parent-first delegation traced line by line across a two-loader chain. | `output/02` |
| `ForNameDemo.java` | `loadClass` and `Class.forName(name, false, l)` do not initialise; `forName(name, true, l)` does. | `output/03` |
| `ErrorsDemo.java` | `ClassNotFoundException`; `NoClassDefFoundError` from a deleted dependency; `NoClassDefFoundError: Could not initialize class`. | `output/04` |
| `PluginDemo.java` + `PluginLoader.java` + `Registry.java` | Class identity, the failing `(Plugin)` cast, hot reload, unloading and a leak. | `output/05` |
| `ContextLoaderDemo.java` | `ServiceLoader` and the thread context class loader. | `output/06` |
| (JVM logging) | `-Xlog:class+load` for the classes in demo 1. | `output/07` |
| (JVM logging) | `-Xlog:class+unload` while the unloading demo runs. | `output/08` |
| `HoldDemo.java` | A live JVM with two named plugin loaders, inspected with `jcmd VM.classloaders`. | `output/09` |
| `ClassLoaderContractTest.java` | Pins every claim above as an assertion. | `output/10` |
| `plugins/*` | The plugin sources the demos compile at run time (`v1`, `v2`, `lib`, `uses-lib`, `missing`, `initfail`, `noisy`). | |
## License
MIT - see the [repo-wide LICENSE](../LICENSE).
+26
View File
@@ -0,0 +1,26 @@
== Which loader defined each class ==
java.lang.String -> null (the bootstrap loader)
java.util.ArrayList -> null (the bootstrap loader)
java.sql.Driver -> 'platform' (jdk.internal.loader.ClassLoaders$PlatformClassLoader)
javax.tools.JavaCompiler -> 'platform' (jdk.internal.loader.ClassLoaders$PlatformClassLoader)
HierarchyDemo (this class) -> 'app' (jdk.internal.loader.ClassLoaders$AppClassLoader)
int[] -> null (the bootstrap loader)
HierarchyDemo[] -> 'app' (jdk.internal.loader.ClassLoaders$AppClassLoader)
== The parent chain, starting from the system (application) loader ==
-> 'app' (jdk.internal.loader.ClassLoaders$AppClassLoader)
-> 'platform' (jdk.internal.loader.ClassLoaders$PlatformClassLoader)
-> null (the bootstrap loader has no parent object)
getPlatformClassLoader() == getSystemClassLoader().getParent(): true
Thread context class loader of main: 'app' (jdk.internal.loader.ClassLoaders$AppClassLoader)
== Modules by defining loader (JDK 25) ==
app 19 modules, e.g. [jdk.attach, jdk.compiler, jdk.editpad, jdk.internal.ed]
bootstrap 21 modules, e.g. [java.base, java.datatransfer, java.desktop, java.instrument]
platform 21 modules, e.g. [java.compiler, java.net.http, java.scripting, java.security.jgss]
== Named module vs unnamed module ==
String.class.getModule() -> module java.base
HierarchyDemo.class.getModule() -> named? false (class-path classes live in the loader's unnamed module)
+20
View File
@@ -0,0 +1,20 @@
== child.loadClass("com.acme.UsesLib") ==
[child] loadClass(com.acme.UsesLib)
[shared] loadClass(com.acme.UsesLib)
[shared] findClass(com.acme.UsesLib) -> not in my directory
[child] findClass(com.acme.UsesLib) -> defineClass
defined by: 'child' (com.ankurm.classloaders.DirLoader)
== Running it: UsesLib needs Lib, which triggers a second load ==
[child] loadClass(com.acme.shared.Lib)
[shared] loadClass(com.acme.shared.Lib)
[shared] findClass(com.acme.shared.Lib) -> defineClass
result: UsesLib called Lib
== Where did Lib end up? ==
[child] loadClass(com.acme.shared.Lib)
Lib defined by: 'shared' (com.ankurm.classloaders.DirLoader) (the parent, not the loader that was asked)
== A JDK class never reaches the child's own directory ==
java.lang.String defined by: null (the bootstrap loader)
@@ -0,0 +1,13 @@
== loadClass: loads and links, does NOT initialise ==
loaded com.acme.Noisy, nothing printed above this line
== Class.forName(name, false, loader): same, explicitly ==
loaded com.acme.Noisy, nothing printed above this line
== First real use triggers initialisation (static method call) ==
>> Noisy static initialiser ran
== Class.forName(name, true, loader): loads and initialises immediately ==
>> Noisy static initialiser ran
done
+18
View File
@@ -0,0 +1,18 @@
== 1. ClassNotFoundException: asking by name for a class nobody has ==
java.lang.ClassNotFoundException: com.acme.DoesNotExist
checked exception? true
== 2. NoClassDefFoundError: compiled against Dep, Dep.class missing at run time ==
with Dep.class present: Dep is here
...Dep.class deleted from disk...
same loader, Dep already loaded: Dep is here (the loader cached it)
fresh loader, Dep never loaded:
java.lang.NoClassDefFoundError: com/acme/missing/Dep
caused by: java.lang.ClassNotFoundException: com.acme.missing.Dep
is an Error, not an Exception: true
== 3. NoClassDefFoundError: "Could not initialize class" (the class file is fine) ==
attempt 1: java.lang.ExceptionInInitializerError, cause java.lang.NumberFormatException: For input string: "not-a-number"
attempt 2: java.lang.NoClassDefFoundError: Could not initialize class com.acme.initfail.Broken
cause: java.lang.ExceptionInInitializerError: Exception java.lang.NumberFormatException: For input string: "not-a-number" [in thread "main"]
+24
View File
@@ -0,0 +1,24 @@
== Class identity = name + defining loader ==
same name: true
same Class object: false
c1 loader: 'plugin-v1' (com.ankurm.classloaders.PluginLoader)
c2 loader: 'plugin-v2' (com.ankurm.classloaders.PluginLoader)
both usable as Plugin (the interface is shared via the parent):
p1.run() = Hello from GreeterPlugin v1
p2.run() = Hello from GreeterPlugin v2
c2.cast(p1): Cannot cast com.acme.GreeterPlugin to com.acme.GreeterPlugin
== The cast that fails even though the names match ==
ClassCastException: class com.acme.GreeterPlugin cannot be cast to class com.ankurm.classloaders.api.Plugin (com.acme.GreeterPlugin is in unnamed module of loader 'plugin-bad' @<hash>; com.ankurm.classloaders.api.Plugin is in unnamed module of loader 'app')
== Hot reload: a fresh loader per version ==
Hello from GreeterPlugin v1
Hello from GreeterPlugin v2
Hello from GreeterPlugin v1
(the same class name, three times, three different Class objects)
== Unloading: a loader is collectable only when nothing reachable points into it ==
plugin dropped, nothing else references it -> loader collected: true
plugin instance stored in static Registry -> loader collected: false
Registry cleared -> (new loader) collected: true
+14
View File
@@ -0,0 +1,14 @@
== ServiceLoader.load(Plugin.class) uses the thread context loader (the app loader) ==
context loader: 'app' (jdk.internal.loader.ClassLoaders$AppClassLoader)
providers found: 0
== ServiceLoader.load(Plugin.class, pluginLoader) names the loader explicitly ==
found com.acme.GreeterPlugin via 'plugin-ctx' (com.ankurm.classloaders.PluginLoader)
providers found: 1
== Or set the context loader for the duration of a call, then restore it ==
context loader: 'plugin-ctx' (com.ankurm.classloaders.PluginLoader)
found com.acme.GreeterPlugin via 'plugin-ctx' (com.ankurm.classloaders.PluginLoader)
providers found: 1
restored: 'app' (jdk.internal.loader.ClassLoaders$AppClassLoader)
@@ -0,0 +1,5 @@
java.lang.String source: shared objects file
java.util.ArrayList source: shared objects file
com.ankurm.classloaders.HierarchyDemo source: file:<module>/target/classes/
java.sql.Driver source: jrt:/java.sql
javax.tools.JavaCompiler source: jrt:/java.compiler
@@ -0,0 +1 @@
9 unloading class com.acme.GreeterPlugin
@@ -0,0 +1,11 @@
<pid>:
+-- <bootstrap>
|
+-- "platform", jdk.internal.loader.ClassLoaders$PlatformClassLoader
|
+-- "app", jdk.internal.loader.ClassLoaders$AppClassLoader
|
+-- "plugin-v1", com.ankurm.classloaders.PluginLoader
|
+-- "plugin-v2", com.ankurm.classloaders.PluginLoader
+3
View File
@@ -0,0 +1,3 @@
[INFO] Tests run: 18, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.027 s -- in com.ankurm.classloaders.ClassLoaderContractTest
[INFO] Tests run: 18, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
@@ -0,0 +1,13 @@
package com.acme.initfail;
import com.ankurm.classloaders.api.Plugin;
/** The class file is present and valid. Its static initialiser throws. */
public class Broken implements Plugin {
static final int LIMIT = Integer.parseInt("not-a-number");
@Override
public String run() {
return "never reached " + LIMIT;
}
}
@@ -0,0 +1,8 @@
package com.acme.shared;
/** A "shared library" class that lives in a different directory (a different loader) than its user. */
public class Lib {
public String name() {
return "Lib";
}
}
@@ -0,0 +1,7 @@
package com.acme.missing;
public class Dep {
public String hello() {
return "Dep is here";
}
}
@@ -0,0 +1,11 @@
package com.acme.missing;
import com.ankurm.classloaders.api.Plugin;
/** Compiles fine against Dep. The demo then deletes Dep.class before running it. */
public class Holder implements Plugin {
@Override
public String run() {
return new Dep().hello();
}
}
@@ -0,0 +1,9 @@
package com.acme;
public class Noisy {
static {
System.out.println(" >> Noisy static initialiser ran");
}
public static void touch() {}
}
@@ -0,0 +1,11 @@
package com.acme;
import com.acme.shared.Lib;
import com.ankurm.classloaders.api.Plugin;
public class UsesLib implements Plugin {
@Override
public String run() {
return "UsesLib called " + new Lib().name(); // forces a second class load, of Lib
}
}
@@ -0,0 +1,10 @@
package com.acme;
import com.ankurm.classloaders.api.Plugin;
public class GreeterPlugin implements Plugin {
@Override
public String run() {
return "Hello from GreeterPlugin v1";
}
}
@@ -0,0 +1,10 @@
package com.acme;
import com.ankurm.classloaders.api.Plugin;
public class GreeterPlugin implements Plugin {
@Override
public String run() {
return "Hello from GreeterPlugin v2";
}
}
+47
View File
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ankurm</groupId>
<artifactId>java-core-examples</artifactId>
<version>1.0</version>
</parent>
<artifactId>classloaders</artifactId>
<name>classloaders</name>
<description>Java class loaders: the three built-in loaders, parent delegation traced, a child-first plugin loader, class identity, hot reload and unloading, and ClassNotFoundException vs NoClassDefFoundError.</description>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<release>25</release>
<compilerArgs><arg>-Xlint:-deprecation</arg></compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<argLine>-Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Regenerates every file in output/. Module counts depend on the JDK build; the GC-based
# unloading demo asks the collector politely and can, in principle, vary (see the post).
set -euo pipefail
cd "$(dirname "$0")/.."
mvn -q -B compile
mkdir -p output
strip() { grep -v -e '^Picked up JAVA_TOOL_OPTIONS' -e '^Picked up _JAVA_OPTIONS'; }
run() { java -Dstdout.encoding=UTF-8 -cp target/classes "com.ankurm.classloaders.$1" 2>&1 | strip > "output/$2.txt"; }
run HierarchyDemo 01-hierarchy
run DelegationDemo 02-delegation
run ForNameDemo 03-forname-vs-loadclass
run ErrorsDemo 04-errors
run PluginDemo 05-plugins
run ContextLoaderDemo 06-context-loader
# 07: what the JVM itself logs about where each class came from (-Xlog:class+load, no decorators)
java -Dstdout.encoding=UTF-8 -Xlog:class+load=info:stdout:none -cp target/classes com.ankurm.classloaders.HierarchyDemo 2>&1 \
| strip | grep -E '^(java\.lang\.String|java\.util\.ArrayList|java\.sql\.Driver|javax\.tools\.JavaCompiler|com\.ankurm\.classloaders\.HierarchyDemo) source: ' \
| sed -E 's#file:/.*/target/classes/#file:<module>/target/classes/#' > output/07-class-load-log.txt
# 08: the JVM's own record of unloads (-Xlog:class+unload) while the unloading demo runs
java -Dstdout.encoding=UTF-8 -Xlog:class+unload=info:stdout:none -cp target/classes com.ankurm.classloaders.PluginDemo 2>&1 \
| strip | grep -E 'unloading class com\.acme' | sed -E 's/ 0x[0-9a-f]+//' | sort | uniq -c > output/08-class-unload-log.txt
# 09: jcmd VM.classloaders against a live JVM holding two named plugin loaders
java -cp target/classes com.ankurm.classloaders.HoldDemo > /tmp/hold.out 2>&1 &
HOLD=$!
for i in $(seq 1 60); do grep -q '^ready' /tmp/hold.out 2>/dev/null && break; sleep 0.5; done
jcmd "$HOLD" VM.classloaders 2>&1 | strip | sed -E "s/^$HOLD:/<pid>:/; s/0x[0-9a-f]+/0x<addr>/g" > output/09-jcmd-classloaders.txt
kill "$HOLD" 2>/dev/null || true
mvn -B test 2>&1 | grep -E 'Tests run|BUILD|ERROR|FAIL' | grep -v 'Picked up' > output/10-tests.txt
echo "regenerated:"; ls output
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Run one demo: scripts/run.sh HierarchyDemo
set -euo pipefail
cd "$(dirname "$0")/.."
mvn -q -B compile
java -Dstdout.encoding=UTF-8 -cp target/classes "com.ankurm.classloaders.${1:?demo class name}"
@@ -0,0 +1,50 @@
package com.ankurm.classloaders;
import com.ankurm.classloaders.api.Plugin;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ServiceLoader;
/**
* The thread context class loader: how a library loaded by a parent loader (ServiceLoader, JDBC,
* JNDI) can still find classes that only a child loader can see.
*/
public class ContextLoaderDemo {
public static void main(String[] args) throws Exception {
Path classes = Util.compile(Util.pluginSources("v1"));
Path services = classes.resolve("META-INF/services");
Files.createDirectories(services);
Files.writeString(services.resolve(Plugin.class.getName()), "com.acme.GreeterPlugin\n");
PluginLoader plugin = new PluginLoader("plugin-ctx", new URL[] {Util.url(classes)},
ClassLoader.getSystemClassLoader(), n -> n.startsWith("com.acme."));
Util.section("ServiceLoader.load(Plugin.class) uses the thread context loader (the app loader)");
System.out.println(" context loader: " + Util.describe(Thread.currentThread().getContextClassLoader()));
System.out.println(" providers found: " + count(ServiceLoader.load(Plugin.class)));
Util.section("ServiceLoader.load(Plugin.class, pluginLoader) names the loader explicitly");
System.out.println(" providers found: " + count(ServiceLoader.load(Plugin.class, plugin)));
Util.section("Or set the context loader for the duration of a call, then restore it");
ClassLoader saved = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(plugin);
try {
System.out.println(" context loader: " + Util.describe(Thread.currentThread().getContextClassLoader()));
System.out.println(" providers found: " + count(ServiceLoader.load(Plugin.class)));
} finally {
Thread.currentThread().setContextClassLoader(saved); // always restore: this is how leaks start
}
System.out.println(" restored: " + Util.describe(Thread.currentThread().getContextClassLoader()));
}
static int count(ServiceLoader<Plugin> sl) {
int n = 0;
for (Plugin p : sl) {
n++;
System.out.println(" found " + p.getClass().getName() + " via " + Util.describe(p.getClass().getClassLoader()));
}
return n;
}
}
@@ -0,0 +1,35 @@
package com.ankurm.classloaders;
import com.ankurm.classloaders.api.Plugin;
import java.nio.file.Path;
/**
* Parent delegation, traced. Two loaders in a chain: {@code shared} (holds Lib) is the parent of
* {@code child} (holds UsesLib). Asking {@code child} for a class makes it ask {@code shared}
* first; only when the parent says "not mine" does {@code child} look in its own directory.
*/
public class DelegationDemo {
public static void main(String[] args) throws Exception {
Path libDir = Util.compile(Util.pluginSources("lib"));
Path usesLibDir = Util.compile(Util.pluginSources("uses-lib"), libDir);
DirLoader shared = new DirLoader("shared", libDir, ClassLoader.getSystemClassLoader(), true);
DirLoader child = new DirLoader("child", usesLibDir, shared, true);
Util.section("child.loadClass(\"com.acme.UsesLib\")");
Class<?> usesLib = child.loadClass("com.acme.UsesLib");
System.out.println(" defined by: " + Util.describe(usesLib.getClassLoader()));
Util.section("Running it: UsesLib needs Lib, which triggers a second load");
Plugin p = (Plugin) usesLib.getDeclaredConstructor().newInstance();
System.out.println(" result: " + p.run());
Util.section("Where did Lib end up?");
Class<?> lib = child.loadClass("com.acme.shared.Lib");
System.out.println(" Lib defined by: " + Util.describe(lib.getClassLoader()) + " (the parent, not the loader that was asked)");
Util.section("A JDK class never reaches the child's own directory");
Class<?> str = child.loadClass("java.lang.String");
System.out.println(" java.lang.String defined by: " + Util.describe(str.getClassLoader()));
}
}
@@ -0,0 +1,51 @@
package com.ankurm.classloaders;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* The smallest useful custom class loader: it reads {@code .class} files from one directory.
*
* <p>It overrides {@code findClass}, not {@code loadClass}, so the default parent-first
* delegation stays intact. {@code loadClass} is overridden only to <em>log</em> the request
* (then calls {@code super}), which is what makes the delegation order visible in the output.
*/
public final class DirLoader extends ClassLoader {
private final Path dir;
private final boolean trace;
public DirLoader(String name, Path dir, ClassLoader parent, boolean trace) {
super(name, parent); // a named loader: shows up as 'name' in error messages and jcmd
this.dir = dir;
this.trace = trace;
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (trace && name.startsWith("com.acme")) {
System.out.println(" [" + getName() + "] loadClass(" + name + ")");
}
return super.loadClass(name, resolve); // findLoadedClass -> parent -> findClass
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Path file = dir.resolve(name.replace('.', '/') + ".class");
if (!Files.exists(file)) {
if (trace && name.startsWith("com.acme")) {
System.out.println(" [" + getName() + "] findClass(" + name + ") -> not in my directory");
}
throw new ClassNotFoundException(name);
}
try {
byte[] bytes = Files.readAllBytes(file);
if (trace && name.startsWith("com.acme")) {
System.out.println(" [" + getName() + "] findClass(" + name + ") -> defineClass");
}
return defineClass(name, bytes, 0, bytes.length);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
}
}
@@ -0,0 +1,74 @@
package com.ankurm.classloaders;
import com.ankurm.classloaders.api.Plugin;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* The two classic errors, produced on purpose, plus the third way to meet NoClassDefFoundError
* (a failed static initialiser). Each scenario prints the real exception and its cause chain.
*/
public class ErrorsDemo {
public static void main(String[] args) throws Exception {
scenario1();
scenario2();
scenario3();
}
/** ClassNotFoundException: you asked for a class by its string name and nobody has it. */
static void scenario1() {
Util.section("1. ClassNotFoundException: asking by name for a class nobody has");
try {
Class.forName("com.acme.DoesNotExist");
} catch (ClassNotFoundException e) {
System.out.println(" " + e.getClass().getName() + ": " + e.getMessage());
System.out.println(" checked exception? " + !RuntimeException.class.isAssignableFrom(e.getClass()));
}
}
/** NoClassDefFoundError: the class compiled against Dep, and Dep.class is gone at run time. */
static void scenario2() throws Exception {
Util.section("2. NoClassDefFoundError: compiled against Dep, Dep.class missing at run time");
Path dir = Util.compile(Util.pluginSources("missing"));
ClassLoader loader = new DirLoader("missing-demo", dir, ClassLoader.getSystemClassLoader(), false);
Plugin first = (Plugin) loader.loadClass("com.acme.missing.Holder").getDeclaredConstructor().newInstance();
System.out.println(" with Dep.class present: " + first.run());
Files.delete(dir.resolve("com/acme/missing/Dep.class"));
System.out.println(" ...Dep.class deleted from disk...");
System.out.println(" same loader, Dep already loaded: " + first.run() + " (the loader cached it)");
ClassLoader fresh = new DirLoader("missing-demo-2", dir, ClassLoader.getSystemClassLoader(), false);
Plugin second = (Plugin) fresh.loadClass("com.acme.missing.Holder").getDeclaredConstructor().newInstance();
try {
second.run();
} catch (NoClassDefFoundError e) {
System.out.println(" fresh loader, Dep never loaded:");
System.out.println(" " + e.getClass().getName() + ": " + e.getMessage());
System.out.println(" caused by: " + e.getCause());
System.out.println(" is an Error, not an Exception: " + !Exception.class.isAssignableFrom(e.getClass()));
}
}
/** The one nobody expects: the class IS there, its static initialiser failed on first use. */
static void scenario3() throws Exception {
Util.section("3. NoClassDefFoundError: \"Could not initialize class\" (the class file is fine)");
Path dir = Util.compile(Util.pluginSources("initfail"));
ClassLoader loader = new DirLoader("initfail-demo", dir, ClassLoader.getSystemClassLoader(), false);
Class<?> broken = loader.loadClass("com.acme.initfail.Broken");
for (int attempt = 1; attempt <= 2; attempt++) {
try {
broken.getDeclaredConstructor().newInstance();
} catch (ExceptionInInitializerError e) {
System.out.println(" attempt " + attempt + ": " + e.getClass().getName() + ", cause " + e.getCause());
} catch (NoClassDefFoundError e) {
System.out.println(" attempt " + attempt + ": " + e.getClass().getName() + ": " + e.getMessage());
System.out.println(" cause: " + e.getCause());
} catch (Exception e) {
System.out.println(" attempt " + attempt + ": " + e);
}
}
}
}
@@ -0,0 +1,28 @@
package com.ankurm.classloaders;
import java.nio.file.Path;
/** Class.forName vs ClassLoader.loadClass: both load, only one initialises. */
public class ForNameDemo {
public static void main(String[] args) throws Exception {
Path dir = Util.compile(Util.pluginSources("noisy"));
Util.section("loadClass: loads and links, does NOT initialise");
ClassLoader a = new DirLoader("a", dir, ClassLoader.getSystemClassLoader(), false);
Class<?> c1 = a.loadClass("com.acme.Noisy");
System.out.println(" loaded " + c1.getName() + ", nothing printed above this line");
Util.section("Class.forName(name, false, loader): same, explicitly");
ClassLoader b = new DirLoader("b", dir, ClassLoader.getSystemClassLoader(), false);
Class<?> c2 = Class.forName("com.acme.Noisy", false, b);
System.out.println(" loaded " + c2.getName() + ", nothing printed above this line");
Util.section("First real use triggers initialisation (static method call)");
c2.getMethod("touch").invoke(null);
Util.section("Class.forName(name, true, loader): loads and initialises immediately");
ClassLoader c = new DirLoader("c", dir, ClassLoader.getSystemClassLoader(), false);
Class.forName("com.acme.Noisy", true, c);
System.out.println(" done");
}
}
@@ -0,0 +1,50 @@
package com.ankurm.classloaders;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
/** Who loaded what: the three built-in loaders, the parent chain, and which modules each owns. */
public class HierarchyDemo {
public static void main(String[] args) {
Util.section("Which loader defined each class");
show("java.lang.String", String.class);
show("java.util.ArrayList", java.util.ArrayList.class);
show("java.sql.Driver", java.sql.Driver.class);
show("javax.tools.JavaCompiler", javax.tools.JavaCompiler.class);
show("HierarchyDemo (this class)", HierarchyDemo.class);
show("int[]", int[].class);
show("HierarchyDemo[]", HierarchyDemo[].class);
Util.section("The parent chain, starting from the system (application) loader");
int depth = 0;
for (ClassLoader cl = ClassLoader.getSystemClassLoader(); cl != null; cl = cl.getParent()) {
System.out.println(" ".repeat(depth) + "-> " + Util.describe(cl));
depth++;
}
System.out.println(" ".repeat(depth) + "-> null (the bootstrap loader has no parent object)");
System.out.println();
System.out.println("getPlatformClassLoader() == getSystemClassLoader().getParent(): "
+ (ClassLoader.getPlatformClassLoader() == ClassLoader.getSystemClassLoader().getParent()));
System.out.println("Thread context class loader of main: " + Util.describe(Thread.currentThread().getContextClassLoader()));
Util.section("Modules by defining loader (JDK " + Runtime.version().feature() + ")");
Map<String, TreeSet<String>> byLoader = new TreeMap<>();
for (Module m : ModuleLayer.boot().modules()) {
ClassLoader cl = m.getClassLoader();
String key = cl == null ? "bootstrap" : cl.getName();
byLoader.computeIfAbsent(key, k -> new TreeSet<>()).add(m.getName());
}
byLoader.forEach((loader, mods) -> System.out.println(
String.format("%-10s %3d modules, e.g. %s", loader, mods.size(), mods.stream().limit(4).toList())));
Util.section("Named module vs unnamed module");
System.out.println("String.class.getModule() -> " + String.class.getModule());
System.out.println("HierarchyDemo.class.getModule() -> named? " + HierarchyDemo.class.getModule().isNamed()
+ " (class-path classes live in the loader's unnamed module)");
}
private static void show(String label, Class<?> c) {
System.out.printf("%-28s -> %s%n", label, Util.describe(c.getClassLoader()));
}
}
@@ -0,0 +1,23 @@
package com.ankurm.classloaders;
import java.net.URL;
import java.nio.file.Path;
/**
* Keeps two named plugin loaders alive and waits, so {@code jcmd <pid> VM.classloaders} has
* something to show. scripts/run-all.sh drives it; it exits by itself after 30 seconds.
*/
public class HoldDemo {
public static void main(String[] args) throws Exception {
Path v1 = Util.compile(Util.pluginSources("v1"));
Path v2 = Util.compile(Util.pluginSources("v2"));
PluginLoader l1 = new PluginLoader("plugin-v1", new URL[] {Util.url(v1)}, ClassLoader.getSystemClassLoader(), n -> n.startsWith("com.acme."));
PluginLoader l2 = new PluginLoader("plugin-v2", new URL[] {Util.url(v2)}, ClassLoader.getSystemClassLoader(), n -> n.startsWith("com.acme."));
l1.loadClass("com.acme.GreeterPlugin");
l2.loadClass("com.acme.GreeterPlugin");
System.out.println("ready");
System.out.flush();
Thread.sleep(30_000);
System.out.println(l1.getName() + " " + l2.getName()); // keep both reachable until here
}
}
@@ -0,0 +1,104 @@
package com.ankurm.classloaders;
import com.ankurm.classloaders.api.Plugin;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.nio.file.Path;
/**
* A plugin host in miniature: one class name, two versions, class identity, the cast that
* fails with a message that looks like a lie, hot reload, and unloading (and not unloading).
*/
public class PluginDemo {
static final ClassLoader APP = ClassLoader.getSystemClassLoader();
public static void main(String[] args) throws Exception {
Path v1 = Util.compile(Util.pluginSources("v1"));
Path v2 = Util.compile(Util.pluginSources("v2"));
identity(v1, v2);
castFailure(v1);
hotReload(v1, v2);
unloading(v1);
}
/** Same fully-qualified name, two loaders: two different, unrelated classes. */
static void identity(Path v1, Path v2) throws Exception {
Util.section("Class identity = name + defining loader");
PluginLoader l1 = new PluginLoader("plugin-v1", new URL[] {Util.url(v1)}, APP, n -> n.startsWith("com.acme."));
PluginLoader l2 = new PluginLoader("plugin-v2", new URL[] {Util.url(v2)}, APP, n -> n.startsWith("com.acme."));
Class<?> c1 = l1.loadClass("com.acme.GreeterPlugin");
Class<?> c2 = l2.loadClass("com.acme.GreeterPlugin");
System.out.println(" same name: " + c1.getName().equals(c2.getName()));
System.out.println(" same Class object: " + (c1 == c2));
System.out.println(" c1 loader: " + Util.describe(c1.getClassLoader()));
System.out.println(" c2 loader: " + Util.describe(c2.getClassLoader()));
Plugin p1 = (Plugin) c1.getDeclaredConstructor().newInstance();
Plugin p2 = (Plugin) c2.getDeclaredConstructor().newInstance();
System.out.println(" both usable as Plugin (the interface is shared via the parent):");
System.out.println(" p1.run() = " + p1.run());
System.out.println(" p2.run() = " + p2.run());
try {
c2.cast(p1);
} catch (ClassCastException e) {
System.out.println(" c2.cast(p1): " + Util.stable(e.getMessage()));
}
}
/** The plugin loader also loads its own copy of the interface: the cast to Plugin fails. */
static void castFailure(Path v1) throws Exception {
Util.section("The cast that fails even though the names match");
URL[] urls = {Util.url(v1), Util.url(Util.hostClasses())};
// BAD: child-first for the API package too, so the plugin gets its own private Plugin interface.
PluginLoader bad = new PluginLoader("plugin-bad", urls, APP,
n -> n.startsWith("com.acme.") || n.startsWith("com.ankurm.classloaders.api."));
Object o = bad.loadClass("com.acme.GreeterPlugin").getDeclaredConstructor().newInstance();
try {
Plugin p = (Plugin) o;
System.out.println(" unexpectedly worked: " + p.run());
} catch (ClassCastException e) {
System.out.println(" ClassCastException: " + Util.stable(e.getMessage()));
}
}
/** One new loader per version; the old one is dropped and becomes garbage. */
static void hotReload(Path v1, Path v2) throws Exception {
Util.section("Hot reload: a fresh loader per version");
for (Path dir : new Path[] {v1, v2, v1}) {
try (PluginLoader l = new PluginLoader("reload", new URL[] {Util.url(dir)}, APP, n -> n.startsWith("com.acme."))) {
Plugin p = (Plugin) l.loadClass("com.acme.GreeterPlugin").getDeclaredConstructor().newInstance();
System.out.println(" " + p.run());
}
}
System.out.println(" (the same class name, three times, three different Class objects)");
}
static void unloading(Path v1) throws Exception {
Util.section("Unloading: a loader is collectable only when nothing reachable points into it");
System.out.println(" plugin dropped, nothing else references it -> loader collected: " + collected(load(v1, false)));
Registry.clear();
System.out.println(" plugin instance stored in static Registry -> loader collected: " + collected(load(v1, true)));
Registry.clear();
System.out.println(" Registry cleared -> (new loader) collected: " + collected(load(v1, false)));
}
/** Loads the plugin in a fresh loader, optionally leaks it, returns only a weak reference to the loader. */
static WeakReference<ClassLoader> load(Path dir, boolean leak) throws Exception {
PluginLoader l = new PluginLoader("transient", new URL[] {Util.url(dir)}, APP, n -> n.startsWith("com.acme."));
Plugin p = (Plugin) l.loadClass("com.acme.GreeterPlugin").getDeclaredConstructor().newInstance();
p.run();
if (leak) Registry.register(p);
return new WeakReference<>(l);
}
/** Asks for GC repeatedly; GC is a request, so give it several chances before concluding "no". */
static boolean collected(WeakReference<ClassLoader> ref) throws InterruptedException {
for (int i = 0; i < 30 && ref.get() != null; i++) {
System.gc();
Thread.sleep(20);
}
return ref.get() == null;
}
}
@@ -0,0 +1,48 @@
package com.ankurm.classloaders;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.function.Predicate;
/**
* A plugin loader that breaks parent-first delegation on purpose: classes the
* {@code selfFirst} predicate accepts are searched in the plugin's own URLs
* <em>before</em> asking the parent. This is the model servlet containers and IDE plugin
* systems use so a plugin can ship its own version of a library.
*
* <p>{@code java.*} is never child-first (the JVM refuses to let any loader but the
* bootstrap/platform ones define it), and everything not matched falls back to the normal
* parent-first path.
*/
public final class PluginLoader extends URLClassLoader {
static {
// Required for loaders that can load classes concurrently without deadlocking.
ClassLoader.registerAsParallelCapable();
}
private final Predicate<String> selfFirst;
public PluginLoader(String name, URL[] urls, ClassLoader parent, Predicate<String> selfFirst) {
super(name, urls, parent);
this.selfFirst = selfFirst;
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> c = findLoadedClass(name);
if (c == null && !name.startsWith("java.") && selfFirst.test(name)) {
try {
c = findClass(name); // look in my own URLs first
} catch (ClassNotFoundException notHere) {
// fall through to the parent
}
}
if (c == null) {
return super.loadClass(name, resolve); // parent-first for everything else
}
if (resolve) resolveClass(c);
return c;
}
}
}
@@ -0,0 +1,25 @@
package com.ankurm.classloaders;
import com.ankurm.classloaders.api.Plugin;
import java.util.ArrayList;
import java.util.List;
/**
* A static registry in the <em>host</em> application. Anything put in here is reachable from
* the application class loader, which is a GC root for as long as the JVM runs. If a plugin
* instance lands in this list, the plugin's class loader (and every class it defined) can
* never be unloaded. This is the classic class-loader leak, in eight lines.
*/
public final class Registry {
private Registry() {}
private static final List<Plugin> KEEP = new ArrayList<>();
public static void register(Plugin p) {
KEEP.add(p);
}
public static void clear() {
KEEP.clear();
}
}
@@ -0,0 +1,79 @@
package com.ankurm.classloaders;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
/** Printing and compile-at-runtime helpers shared by the demos and the tests. */
public final class Util {
private Util() {}
public static void section(String title) {
System.out.println();
System.out.println("== " + title + " ==");
}
/** Where the compiled host classes (including the Plugin interface) live. */
public static Path hostClasses() {
try {
return Path.of(com.ankurm.classloaders.api.Plugin.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (java.net.URISyntaxException e) {
throw new IllegalStateException(e);
}
}
/** The plugin sources directory, relative to the module directory (the working directory). */
public static Path pluginSources(String name) {
return Path.of("plugins", name);
}
/**
* Compiles every .java file under {@code src} into a fresh temp directory and returns it.
* The host classes are always on the compile class path; {@code extraClassPath} adds more.
*/
public static Path compile(Path src, Path... extraClassPath) {
try {
Path out = Files.createTempDirectory("cl-demo-");
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
List<Path> files;
try (Stream<Path> s = Files.walk(src)) {
files = s.filter(p -> p.toString().endsWith(".java")).toList();
}
StringBuilder cp = new StringBuilder(hostClasses().toString());
for (Path p : extraClassPath) cp.append(java.io.File.pathSeparator).append(p);
List<String> args = new java.util.ArrayList<>(List.of("-d", out.toString(), "-cp", cp.toString(), "--release", "25", "-proc:none"));
files.forEach(f -> args.add(f.toString()));
int rc = javac.run(null, null, null, args.toArray(String[]::new));
if (rc != 0) throw new IllegalStateException("javac failed for " + src);
return out;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static URL url(Path dir) {
try {
return dir.toUri().toURL();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
/** Strips identity hash codes such as {@code @1b2c3d} so transcripts stay stable between runs. */
public static String stable(String s) {
return s.replaceAll("@[0-9a-f]{4,}", "@<hash>");
}
/** Describes a loader the way a human wants to read it. */
public static String describe(ClassLoader cl) {
if (cl == null) return "null (the bootstrap loader)";
return (cl.getName() == null ? "<unnamed>" : "'" + cl.getName() + "'") + " (" + cl.getClass().getName() + ")";
}
}
@@ -0,0 +1,11 @@
package com.ankurm.classloaders.api;
/**
* The contract between the host application and a plugin. This interface lives in the
* application class path, so every plugin loader that delegates to the application loader
* sees exactly one copy of it. That single shared copy is what makes
* {@code (Plugin) instance} work across loaders.
*/
public interface Plugin {
String run();
}
@@ -0,0 +1,225 @@
package com.ankurm.classloaders;
import static org.junit.jupiter.api.Assertions.*;
import com.ankurm.classloaders.api.Plugin;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ServiceLoader;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/** Pins every claim the post makes about class loaders as an assertion. */
class ClassLoaderContractTest {
static final ClassLoader APP = ClassLoader.getSystemClassLoader();
static Path v1, v2;
@BeforeAll
static void compilePlugins() {
v1 = Util.compile(Util.pluginSources("v1"));
v2 = Util.compile(Util.pluginSources("v2"));
}
static PluginLoader loader(String name, Path dir) {
return new PluginLoader(name, new URL[] {Util.url(dir)}, APP, n -> n.startsWith("com.acme."));
}
// ---- the three built-in loaders ----
@Test
void javaBaseClassesHaveANullLoader() {
assertNull(String.class.getClassLoader());
assertNull(java.util.ArrayList.class.getClassLoader());
assertNull(int[].class.getClassLoader());
}
@Test
void platformAndAppLoadersAreNamed() {
assertEquals("platform", ClassLoader.getPlatformClassLoader().getName());
assertEquals("app", APP.getName());
assertSame(ClassLoader.getPlatformClassLoader(), APP.getParent());
assertNull(ClassLoader.getPlatformClassLoader().getParent());
}
@Test
void javaSqlIsPlatformAndTheDemoClassIsApp() {
assertSame(ClassLoader.getPlatformClassLoader(), java.sql.Driver.class.getClassLoader());
assertSame(APP, ClassLoaderContractTest.class.getClassLoader());
}
@Test
void arrayClassUsesTheElementTypesLoader() {
assertSame(ClassLoaderContractTest.class.getClassLoader(), ClassLoaderContractTest[].class.getClassLoader());
}
@Test
void everyBootModuleBelongsToExactlyOneOfThreeLoaders() {
for (Module m : ModuleLayer.boot().modules()) {
ClassLoader cl = m.getClassLoader();
assertTrue(cl == null || cl == ClassLoader.getPlatformClassLoader() || cl == APP, m.getName());
}
assertNull(Object.class.getModule().getClassLoader());
}
// ---- parent delegation ----
@Test
void childAsksParentFirstAndTheParentDefinesTheClass() throws Exception {
Path libDir = Util.compile(Util.pluginSources("lib"));
Path usesLibDir = Util.compile(Util.pluginSources("uses-lib"), libDir);
DirLoader shared = new DirLoader("shared", libDir, APP, false);
DirLoader child = new DirLoader("child", usesLibDir, shared, false);
Class<?> usesLib = child.loadClass("com.acme.UsesLib");
assertSame(child, usesLib.getClassLoader());
Class<?> lib = child.loadClass("com.acme.shared.Lib");
assertSame(shared, lib.getClassLoader()); // asked the child, defined by the parent
}
@Test
void jdkClassesAlwaysComeFromTheirOwnLoaderEvenWhenAChildIsAsked() throws Exception {
DirLoader d = new DirLoader("empty", Files.createTempDirectory("empty"), APP, false);
assertNull(d.loadClass("java.lang.String").getClassLoader());
}
@Test
void javaPackageCannotBeDefinedByACustomLoader() {
class Definer extends ClassLoader {
Definer() { super("definer", APP); }
void define(String name) { defineClass(name, new byte[8], 0, 8); }
}
SecurityException e = assertThrows(SecurityException.class, () -> new Definer().define("java.lang.Fake"));
assertTrue(e.getMessage().contains("Prohibited package name: java.lang"), e.getMessage());
}
// ---- class identity ----
@Test
void sameNameDifferentLoaderIsADifferentClass() throws Exception {
Class<?> c1 = loader("p1", v1).loadClass("com.acme.GreeterPlugin");
Class<?> c2 = loader("p2", v2).loadClass("com.acme.GreeterPlugin");
assertEquals(c1.getName(), c2.getName());
assertNotSame(c1, c2);
assertFalse(c2.isInstance(c1.getDeclaredConstructor().newInstance()));
}
@Test
void bothVersionsAreUsableThroughTheSharedInterface() throws Exception {
Plugin p1 = (Plugin) loader("p1", v1).loadClass("com.acme.GreeterPlugin").getDeclaredConstructor().newInstance();
Plugin p2 = (Plugin) loader("p2", v2).loadClass("com.acme.GreeterPlugin").getDeclaredConstructor().newInstance();
assertEquals("Hello from GreeterPlugin v1", p1.run());
assertEquals("Hello from GreeterPlugin v2", p2.run());
}
@Test
void loadingTheApiChildFirstBreaksTheCast() throws Exception {
PluginLoader bad = new PluginLoader("plugin-bad", new URL[] {Util.url(v1), Util.url(Util.hostClasses())}, APP,
n -> n.startsWith("com.acme.") || n.startsWith("com.ankurm.classloaders.api."));
Object o = bad.loadClass("com.acme.GreeterPlugin").getDeclaredConstructor().newInstance();
ClassCastException e = assertThrows(ClassCastException.class, () -> {
Plugin p = (Plugin) o;
p.run();
});
assertTrue(e.getMessage().contains("cannot be cast to class com.ankurm.classloaders.api.Plugin"), e.getMessage());
assertTrue(e.getMessage().contains("loader 'plugin-bad'"), e.getMessage());
assertTrue(e.getMessage().contains("loader 'app'"), e.getMessage());
}
// ---- Class.forName vs loadClass ----
@Test
void loadClassDoesNotInitialiseButForNameTrueDoes() throws Exception {
Path dir = Util.compile(Util.pluginSources("noisy"));
var out = new java.io.ByteArrayOutputStream();
var old = System.out;
System.setOut(new java.io.PrintStream(out, true));
try {
new DirLoader("a", dir, APP, false).loadClass("com.acme.Noisy");
Class.forName("com.acme.Noisy", false, new DirLoader("b", dir, APP, false));
assertEquals("", out.toString());
Class.forName("com.acme.Noisy", true, new DirLoader("c", dir, APP, false));
} finally {
System.setOut(old);
}
assertTrue(out.toString().contains("Noisy static initialiser ran"));
}
// ---- the two errors ----
@Test
void classNotFoundExceptionIsCheckedAndComesFromAStringLookup() {
ClassNotFoundException e = assertThrows(ClassNotFoundException.class, () -> Class.forName("com.acme.DoesNotExist"));
assertEquals("com.acme.DoesNotExist", e.getMessage());
assertFalse(RuntimeException.class.isAssignableFrom(ClassNotFoundException.class));
}
@Test
void noClassDefFoundErrorWhenACompiledDependencyIsGone() throws Exception {
Path dir = Util.compile(Util.pluginSources("missing"));
Files.delete(dir.resolve("com/acme/missing/Dep.class"));
Plugin holder = (Plugin) new DirLoader("m", dir, APP, false).loadClass("com.acme.missing.Holder")
.getDeclaredConstructor().newInstance();
NoClassDefFoundError e = assertThrows(NoClassDefFoundError.class, holder::run);
assertEquals("com/acme/missing/Dep", e.getMessage()); // slashes: the JVM's internal name
assertInstanceOf(ClassNotFoundException.class, e.getCause());
assertEquals("com.acme.missing.Dep", e.getCause().getMessage());
assertTrue(Error.class.isAssignableFrom(NoClassDefFoundError.class));
}
@Test
void alreadyLoadedDependencySurvivesDeletionInTheSameLoader() throws Exception {
Path dir = Util.compile(Util.pluginSources("missing"));
Plugin holder = (Plugin) new DirLoader("m", dir, APP, false).loadClass("com.acme.missing.Holder")
.getDeclaredConstructor().newInstance();
assertEquals("Dep is here", holder.run());
Files.delete(dir.resolve("com/acme/missing/Dep.class"));
assertEquals("Dep is here", holder.run());
}
@Test
void failedStaticInitialiserFirstThrowsEiiThenNoClassDefFoundErrorWithCause() throws Exception {
Path dir = Util.compile(Util.pluginSources("initfail"));
Class<?> broken = new DirLoader("i", dir, APP, false).loadClass("com.acme.initfail.Broken");
ExceptionInInitializerError first = assertThrows(ExceptionInInitializerError.class,
() -> broken.getDeclaredConstructor().newInstance());
assertInstanceOf(NumberFormatException.class, first.getCause());
NoClassDefFoundError second = assertThrows(NoClassDefFoundError.class,
() -> broken.getDeclaredConstructor().newInstance());
assertEquals("Could not initialize class com.acme.initfail.Broken", second.getMessage());
assertInstanceOf(ExceptionInInitializerError.class, second.getCause()); // JDK 17+ keeps the original
}
// ---- context class loader ----
@Test
void serviceLoaderUsesTheContextLoaderUnlessTold() throws Exception {
Path classes = Util.compile(Util.pluginSources("v1"));
Path services = Files.createDirectories(classes.resolve("META-INF/services"));
Files.writeString(services.resolve(Plugin.class.getName()), "com.acme.GreeterPlugin\n");
PluginLoader pl = loader("ctx", classes);
assertEquals(0, ServiceLoader.load(Plugin.class).stream().count());
assertEquals(1, ServiceLoader.load(Plugin.class, pl).stream().count());
ClassLoader saved = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(pl);
try {
assertEquals(1, ServiceLoader.load(Plugin.class).stream().count());
} finally {
Thread.currentThread().setContextClassLoader(saved);
}
}
// ---- unloading ----
@Test
void aDroppedLoaderIsCollectedButARegistryReferenceKeepsItAlive() throws Exception {
assertTrue(PluginDemo.collected(PluginDemo.load(v1, false)));
WeakReference<ClassLoader> leaked = PluginDemo.load(v1, true);
assertFalse(PluginDemo.collected(leaked));
Registry.clear();
assertTrue(PluginDemo.collected(leaked)); // release the root and the same loader goes
}
}
+1
View File
@@ -45,6 +45,7 @@
<module>random</module>
<module>completablefuture</module>
<module>streams</module>
<module>classloaders</module>
</modules>
<properties>