GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — RecordingAPI JNI global reference prevents class loader unloading · Issue #1811 · async-profiler/async-profiler

RecordingAPI JNI global reference prevents class loader unloading #1811

New issue
Copy link
New issue
Copy link
Closed
alibaba/arthas
#3281
alibaba/arthas#3281
Closed
RecordingAPI JNI global reference prevents class loader unloading#1811
alibaba/arthas
#3281
Copy link

Description

@hengyunabc
hengyunabc
opened on Sep 24, 2026
Issue body actions

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.dylib

The 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=false

The 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.dylib

Output:

version=4.5-a725243
classLoaderCollected=false

Controls, 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.dylib

Results 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 with make -j4 COMMIT_TAG=true; runtime version 4.5-a725243.

Environment details

  • macOS 26.6.2, build 25G83; arm64; not running in a container.
  • Zulu OpenJDK 8u332: 1.8.0_332-b09, Zulu 8.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.

Activity

  1. apangin commented on Sep 24, 2026

    @apangin
    apangin
    on Sep 24, 2026
    Collaborator
    More actions

    I wonder how you found this issue? What was the use case?

    This affects applications that load the profiler into a disposable class loader

    How does this affect applications? Do you know examples of such applications?

  2. hengyunabc commented on Sep 25, 2026

    @hengyunabc
    hengyunabc
    on Sep 25, 2026
    Author
    More actions

    https://github.com/alibaba/arthas
    Arthas is a JVM diagnostic tool that dynamically loads async-profiler. Arthas itself runs using a separate classloader, and the users may start and stop Arthas multiple times.

  3. apangin commented on Sep 25, 2026

    @apangin
    apangin
    on Sep 25, 2026
    Collaborator
    More actions

    Could you please rewrite the issue description in your own words, focusing on the actual impact of the problem?
    The current GenAI dump is unreadable mess, which async-profiler maintainers have neither time nor desire to delve into.
    Furthermore, it's false and misleading. For instance, it claims that the issue is that "native library cannot be unloaded", but that was by design from the very beginning and has never changed.

  4. apangin
    added a commit that references this issue on Oct 8, 2026

    Fixed class-loading bugs #1811, #1818

    ab0cda8
  5. apangin commented on Oct 8, 2026

    @apangin
    apangin
    on Oct 8, 2026
    Collaborator
    More actions

    Fixed in #1819

  6. apangin
    closed this as completedon Oct 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402775 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.