RecordingAPI JNI global reference prevents class loader unloading
Describe the bug
Loading async-profiler through a disposable URLClassLoader retains that class loader after the application has closed it and released all strong references.
Calling AsyncProfiler.getInstance(nativeLibrary) followed by getVersion() is enough to reproduce this. No profiling session needs to be started, and the application does not call Recording or Span. Explicitly starting and stopping a profiling session does not release the class loader either.
I reproduced this with the official 4.5 release and current master at a725243e50f55cdbffc60bc6920ede281192f78a, using JDK 8 and JDK 21.
This affects applications that load the profiler into a disposable class loader, such as reloadable plugins: the loader, its loaded classes/static state, and its native library cannot be unloaded.
Expected vs. actual behavior
Expected: Once the helper method below returns, there is no active profiling session and the caller holds only a WeakReference to the closed loader. The loader should be eligible for collection.
Actual: The loader remains reachable after 30 explicit full-GC/finalization attempts. The same program collects the loader when native loading is skipped, or when Recording/Span are omitted from a separate copy of the API jar.
Reproduction Steps
The reproducer below is a single Java file. It uses only JDK classes and upstream async-profiler artifacts; no build tool, framework, agent attachment, or additional dependency is required.
Save as ProfilerClassLoaderLeak.java:
import java.io.File;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLClassLoader;
public class ProfilerClassLoaderLeak {
private static WeakReference<ClassLoader> loadAndRelease(String[] args) throws Exception {
URL apiJar = new File(args[0]).toURI().toURL();
URLClassLoader loader = new URLClassLoader(new URL[] {apiJar}, null);
try {
Class<?> api = Class.forName("one.profiler.AsyncProfiler", true, loader);
String mode = args.length == 3 ? args[2] : "version";
if (!"no-native".equals(mode)) {
Object profiler = api.getMethod("getInstance", String.class)
.invoke(null, new File(args[1]).getAbsolutePath());
System.out.println("version=" + api.getMethod("getVersion").invoke(profiler));
if ("start-stop".equals(mode)) {
System.out.print(api.getMethod("execute", String.class)
.invoke(profiler, "start,event=cpu"));
Thread.sleep(100);
api.getMethod("stop").invoke(profiler);
System.out.print(api.getMethod("execute", String.class).invoke(profiler, "status"));
}
}
return new WeakReference<ClassLoader>(loader);
} finally {
loader.close();
}
}
public static void main(String[] args) throws Exception {
if (args.length < 2 || args.length > 3
|| (args.length == 3 && !"version".equals(args[2])
&& !"no-native".equals(args[2]) && !"start-stop".equals(args[2]))) {
throw new IllegalArgumentException(
"Usage: java ProfilerClassLoaderLeak <api.jar> <native-library> [version|no-native|start-stop]");
}
WeakReference<ClassLoader> loader = loadAndRelease(args);
for (int i = 0; i < 30 && loader.get() != null; i++) {
System.gc();
System.runFinalization();
Thread.sleep(100);
}
System.out.println("classLoaderCollected=" + (loader.get() == null));
}
}Download the official 4.5 artifacts and run on macOS:
curl -fLO https://github.com/async-profiler/async-profiler/releases/download/v4.5/async-profiler.jar
curl -fLO https://github.com/async-profiler/async-profiler/releases/download/v4.5/async-profiler-4.5-macos.zip
unzip -q async-profiler-4.5-macos.zip
javac ProfilerClassLoaderLeak.java
java -Xint -XX:+UseSerialGC -cp . ProfilerClassLoaderLeak \
async-profiler.jar \
async-profiler-4.5-macos/lib/libasyncProfiler.dylibThe main application class path is just .; the API jar is loaded only by the disposable loader. -Xint avoids JIT local-variable-liveness ambiguity, and Serial GC makes the explicit collection requests useful for this check. Each invocation runs in a fresh JVM and loads the native library once, directly from its original path.
Actual output on both tested JDKs:
version=4.5
classLoaderCollected=falseThe source also accepts a Linux .so path, but my runtime tests were on macOS arm64.
To run the identical reproducer against the latest tested source, build it with JDK 11 or newer:
git clone https://github.com/async-profiler/async-profiler.git async-profiler-src
git -C async-profiler-src checkout a725243e50f55cdbffc60bc6920ede281192f78a
make -C async-profiler-src -j4 COMMIT_TAG=true
java -Xint -XX:+UseSerialGC -cp . ProfilerClassLoaderLeak \
async-profiler-src/build/jar/async-profiler.jar \
async-profiler-src/build/lib/libasyncProfiler.dylibOutput:
version=4.5-a725243
classLoaderCollected=falseControls, using that same master build:
# Skip native loading; the same URLClassLoader is collected.
java -Xint -XX:+UseSerialGC -cp . ProfilerClassLoaderLeak \
async-profiler-src/build/jar/async-profiler.jar \
async-profiler-src/build/lib/libasyncProfiler.dylib no-native
# Explicitly stop a real profiling session; the loader is still retained.
java -Xint -XX:+UseSerialGC -cp . ProfilerClassLoaderLeak \
async-profiler-src/build/jar/async-profiler.jar \
async-profiler-src/build/lib/libasyncProfiler.dylib start-stop
# Remove only the Span API classes from a separate copy of the jar.
cp async-profiler-src/build/jar/async-profiler.jar api-without-span.jar
zip -d api-without-span.jar 'one/profiler/Recording.class' 'one/profiler/Span*.class'
java -Xint -XX:+UseSerialGC -cp . ProfilerClassLoaderLeak \
api-without-span.jar \
async-profiler-src/build/lib/libasyncProfiler.dylibResults with the standalone program:
| API/native combination | Mode | JDK 8: collected | JDK 21: collected |
|---|---|---|---|
| Official 4.5 | version only | false | false |
Master a725243 |
version only | false | false |
Master a725243 |
start, then stop | false | false |
Master a725243 |
skip native loading | true | true |
Master a725243, API jar without Recording/Span |
version only | true | true |
I also compiled and ran the unmodified source in a clean temporary directory containing only this Java file and the official API/native artifacts.
Additional Information/Context
The retaining reference is in RecordingAPI::registerNatives:
_recording_class = (jclass) env->NewGlobalRef(recording_class);The load path reaches it automatically:
AsyncProfiler.getInstance(nativeLibrary)
-> System.load
-> JNI_OnLoad
-> VM::init(vm, true)
-> RecordingAPI::bind
-> FindClass("one/profiler/Recording") / registerNatives
-> NewGlobalRef(recording_class)RecordingAPI::bind is invoked during native initialization, so the application does not need to explicitly use the Span API. The global reference keeps Recording.class and its defining loader alive.
RecordingAPI::stop() only updates the Java state field; it does not release the reference. There is no corresponding DeleteGlobalRef for _recording_class.
JNI_OnUnload only stops the profiler. Also, according to the JNI lifecycle specification, this callback runs when the owning class loader is collected, so moving reference cleanup only into JNI_OnUnload would not break this retention cycle.
The reference originates from the Span API introduced in #1755. I checked existing issues; #1764 concerns repeated method retransformation and lambda classes, while this reproducer only queries the profiler version.
Async-profiler version
- Official release 4.5 (unmodified API jar and macOS native library).
- Master
a725243e50f55cdbffc60bc6920ede281192f78a, built locally withmake -j4 COMMIT_TAG=true; runtime version4.5-a725243.
Environment details
- macOS 26.6.2, build 25G83; arm64; not running in a container.
- Zulu OpenJDK 8u332:
1.8.0_332-b09, Zulu8.62.0.19-CA-macos-aarch64. - Oracle JDK 21.0.1:
21.0.1+12-LTS-29. - The latest source was built with JDK 21; the standalone reproducer was compiled with JDK 8 and run on both JDKs.
Source: async-profiler/async-profiler