async-profiler: Finding Where a Java Program Spends Time

async-profiler is a low-overhead sampling profiler for HotSpot JVMs that sees Java, native and kernel frames and produces flame graphs. This page covers version 4.6: installation, the CPU sampling engines and why containers matter, each profiling mode, and the options that changed. A runnable JDK Flight Recorder program at the end answers the same questions on a small example.

Share

Contents

About this page

The asprof commands below were checked against the documentation and changelog of the async-profiler 4.6 release, but they were not run for this page: the environment used to build it could not load a native profiler. The output of asprof shown in the "First run" section is the sample from the project's own Getting Started guide, and is labeled as such. The last part of the page is a complete Java program that answers the same three questions (where is CPU spent, what allocates, which lock is contended) with JDK Flight Recorder; that program was compiled and run on JDK 25, and its output is real.

What async-profiler is

async-profiler is an open-source sampling profiler for HotSpot-based JVMs (OpenJDK, Oracle JDK, Corretto, Zulu and others). It runs as a native agent inside the target JVM. On a timer, it interrupts threads with a signal and records their call stacks using AsyncGetCallTrace, a HotSpot API that can walk a Java stack at any point, not only at safepoints. On Linux, CPU mode combines those Java stacks with stacks from the kernel's perf_events, so one profile shows Java methods, JVM internals, native libraries and kernel functions together.

Why the "not only at safepoints" part matters: profilers built on standard JVMTI calls such as GetAllStackTraces can only see a thread when it reaches a safepoint, a point where the JVM may pause it. The JIT does not place safepoints everywhere (inside counted loops, for example), so those profilers attribute time to the nearest safepoint instead of the code actually running. This is called safepoint bias.

async-profiler 4.6 at a glance
ItemValue
Current stable release4.6, tagged October 2026 (4.5 was July 2026)
Official buildsLinux x64 and arm64 (.tar.gz), macOS x64 and arm64 (one .zip)
Tools in the packageasprof (attach and control), libasyncProfiler.so (the agent), jfrconv (convert JFR to flame graphs and other formats)
Output formatsflamegraph and tree (HTML), collapsed (text), jfr, otlp (OpenTelemetry), plain text summary
Java APIMaven artifact tools.profiler:async-profiler

Installing and preparing the machine

async-profiler is distributed as a ready-built archive per platform; nothing needs to be compiled. Download and unpack the release for your system, then check that the launcher runs:

Shell
# Linux x64 (use linux-arm64 for ARM servers)
V=4.6
curl -L -O https://github.com/async-profiler/async-profiler/releases/download/v$V/\
async-profiler-$V-linux-x64.tar.gz
tar xzf async-profiler-4.6-linux-x64.tar.gz
cd async-profiler-4.6-linux-x64
bin/asprof --version

# macOS: one zip for both architectures
# https://github.com/async-profiler/async-profiler/releases/download/v4.6/
#   async-profiler-4.6-macos.zip

Two Linux kernel settings decide how much the CPU profiler can see. The project's guide asks for both when you want kernel stacks from a non-root process:

Shell
sudo sysctl kernel.perf_event_paranoid=1   # allow perf_events for normal users
sudo sysctl kernel.kptr_restrict=0         # show kernel symbol names

If the profiler is attached to an already running JVM, start that JVM with -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints. Without it, the JIT keeps debug information only at safepoints, so samples taken elsewhere can be attributed to the wrong inlined method. The guide makes one exception: the flags are not needed when async-profiler is loaded at JVM start-up with -agentpath.

asprof must run as the same user and group as the target JVM, a limit of the HotSpot attach mechanism. Run as root, it switches to that user itself.

First run

Find the process id of the JVM to profile, then attach to it. The same tool starts, stops and inspects a profiling session:

Shell
jps                                     # find the process id, for example 8983
asprof -d 30 -f /tmp/flamegraph.html 8983   # profile CPU for 30 s, write a flame graph
asprof start 8983                       # or start ...
asprof stop -f /tmp/flamegraph.html 8983    # ... and stop by hand
asprof status 8983                      # is a session running?
asprof list 8983                        # events available for this process

In place of the pid you can pass jps (when exactly one Java process runs) or the application name as jps shows it. A file name ending in .html selects the flame graph format; in 4.6 the HTML file contains both the flame graph and a tree view. Without -f, asprof prints a text report. This is the sample from the project's Getting Started guide, trimmed there for length:

Output
--- Execution profile ---
Total samples:           687
Unknown (native):        1 (0.15%)

--- 6790000000 (98.84%) ns, 679 samples
  [ 0] Primes.isPrime
  [ 1] Primes.primesThread
  [ 2] Primes.access$000
  [ 3] Primes$1.run
  [ 4] java.lang.Thread.run

          ns  percent  samples  top
  ----------  -------  -------  ---
  6790000000   98.84%      679  Primes.isPrime
    40000000    0.58%        4  __do_softirq

The first block is the hottest complete stack: Primes.isPrime called from primesThread. The table at the end ranks methods by samples where they were the top frame. At the default interval of 10 ms of CPU time (100 samples per second per busy core), 679 samples are 6.79 seconds of CPU. __do_softirq is a Linux kernel function; it appears because perf_events captured kernel stacks.

To profile from the moment the JVM starts, load the agent directly:

Shell
java -agentpath:/path/to/libasyncProfiler.so=start,event=cpu,file=profile.html -jar app.jar

CPU sampling engines and containers

-e cpu is the default event, but on Linux it can be backed by three different mechanisms. Which one you get decides whether you see kernel frames, and whether profiling works inside a container at all.

CPU engines (from the async-profiler CPU Sampling Engines guide)
EngineMechanismKernel stacksWorks in containers by defaultNotes
cpu (perf_events)One perf_event per thread, a signal every N ns of CPU timeYesNoMost accurate; uses one file descriptor per thread, so a low ulimit -n can run out
ctimertimer_createNoYesLinux only; resolution limited by the kernel tick (10 ms at HZ=100, 4 ms at HZ=250)
itimersetitimer(ITIMER_PROF)NoYesOne signal per process at a time, uneven between threads; the engine used on macOS

With -e cpu, async-profiler first tries to create a test perf_event. If kernel profiling is not allowed, by perf_event_paranoid or by Docker's default seccomp profile, it switches to ctimer without failing. The profile still works, but kernel frames are missing. The engine actually used is recorded in JFR output.

To get full CPU profiles in Docker, the guide gives three choices: relax seccomp (--security-opt seccomp=unconfined, sometimes with --cap-add SYS_ADMIN), run asprof from the host as a privileged user with the host pid of the process (it switches into the container's namespaces itself), or use the --fdtransfer helper. When none is possible, -e ctimer is the honest fallback.

Profiling modes

Main async-profiler events
EventSamplesWhat the top frame and counter meanExample
cpuThreads using CPU, every 10 ms of CPU time by defaultThe method running; counter is CPU timeasprof -e cpu -i 5ms -d 30 -f cpu.html PID
wallAll threads equally, running or not, every interval of real timeWhere each thread is, including sleeping and blockedasprof -e wall -t -i 50ms -f wall.html PID
allocHeap allocations, through HotSpot TLAB callbacksThe class of the allocated object; counter is bytesasprof -e alloc --alloc 500k -d 30 -f alloc.html PID
lockContended Java monitors and java.util.concurrent locksThe class of the lock; counter is nanoseconds spent waiting to enter itasprof -e lock -t -i 5ms -f lock.html PID
nativememmalloc, realloc, calloc and freeAllocations without a matching free (with jfrconv --leak)asprof start -e nativemem -f app.jfr PID
ClassName.methodNameEvery call of one Java methodWho calls itasprof -e java.util.Properties.getProperty -d 10 PID

Details worth knowing before reading the results:

  • Allocation mode does not instrument bytecode and does not stop escape analysis, so allocations the JIT removes are not counted. It samples by size: --alloc 500k takes one sample per 500 KB allocated on average.
  • Wall-clock mode is most useful with -t, which splits the graph per thread. Without it, thousands of idle pool threads waiting on a queue can fill the graph. In 4.6, --ithread and --xthread include or exclude threads by name pattern, for example --ithread 'http-*'.
  • Several events at once need JFR output: asprof -e cpu --alloc 2m --lock 10ms -f profile.jfr PID. --jfrsync profile also starts a normal JFR recording, so GC and other JVM events land in the same file, with execution samples from async-profiler.
  • Instrumenting a Java method (-e ClassName.methodName) when attaching at run time can deoptimize all compiled methods the first time, a visible pause in a large application. Loading the agent at start-up avoids it.

Options that changed

Many guides were written for version 2 or 3. These changes from the 4.6 changelog break commands copied from them:

Breaking changes in async-profiler 4.6
BeforeIn 4.6
--filter "http-nio*" to select threads by namefilter no longer takes arguments; use --ithread 'http-nio*' and --xthread
Embedded HTTP serverRemoved
macOS 10.xmacOS 11 or later

Version 4.6 also added sending profiles straight to an OpenTelemetry endpoint, a rate limiter for JFR events (--ratelimit), and allocation tracking for JEP 401 value classes.

Reading a flame graph

  • Each box is a method. The box under it is its caller, so a column from bottom to top is one call stack.
  • Width is the share of samples that contain that stack. The x-axis is not time: boxes are sorted alphabetically within each level and merged, so neighbours are not "before" and "after".
  • Look for wide boxes near the top. A wide box whose children are all narrow is where time is spent in the method itself (its "self" time).
  • In allocation graphs the top frame is the allocated class, and width is bytes; in lock graphs the top frame is the lock class, and width is wait time.

A runnable equivalent with JDK Flight Recorder

JDK Flight Recorder (JFR) is built into the JDK and can answer the same three questions without a native agent. This program creates one problem of each kind, records it for 3 seconds, and then reads the recording with the jdk.jfr.consumer API to print the top frames, the same kind of "top" table that profilers show. The workload was chosen so each problem has one clear owner:

  • one thread tests numbers for primality with trial division, a pure CPU loop;
  • one thread builds a new string for every number, a pure allocation loop;
  • four threads take turns holding one monitor for 5 ms each, so three are always waiting.
Java
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordedFrame;
import jdk.jfr.consumer.RecordingFile;

// A program with one CPU hot spot, one allocation hot spot and one contended lock,
// profiled with JDK Flight Recorder. Each section prints the top frames, like a profiler.
public class HotSpots {

    static final AtomicBoolean running = new AtomicBoolean(true);
    static final Object LOCK = new Object();
    static long sink;

    // CPU: trial division, deliberately slow
    static boolean isPrime(long n) {
        for (long d = 2; d * d <= n; d++) {
            if (n % d == 0) {
                return false;
            }
        }
        return n > 1;
    }

    static void countPrimes() {
        long count = 0;
        for (long n = 1000000; running.get(); n++) {
            if (isPrime(n)) {
                count++;
            }
        }
        sink += count;
    }

    // Allocation: builds a new String for every number
    static String label(int i) {
        return "item-" + i + "-" + Integer.toHexString(i);
    }

    static void buildLabels() {
        long total = 0;
        for (int i = 0; running.get(); i++) {
            total += label(i).length();
        }
        sink += total;
    }

    // Lock: four threads take turns holding one monitor for 5 ms
    static void updateShared() {
        while (running.get()) {
            synchronized (LOCK) {
                long end = System.nanoTime() + 5000000;
                while (System.nanoTime() < end) {
                    Thread.onSpinWait();
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        try (Recording rec = new Recording()) {
            rec.enable("jdk.ExecutionSample").withPeriod(Duration.ofMillis(10));
            rec.enable("jdk.CPUTimeSample").with("throttle", "10ms");  // JDK 25, Linux only
            rec.enable("jdk.ObjectAllocationSample").with("throttle", "1000/s");
            rec.enable("jdk.JavaMonitorEnter").withThreshold(Duration.ofMillis(1));
            rec.start();

            List<Thread> threads = List.of(
                    Thread.ofPlatform().name("primes").start(HotSpots::countPrimes),
                    Thread.ofPlatform().name("labels").start(HotSpots::buildLabels),
                    Thread.ofPlatform().name("shared-1").start(HotSpots::updateShared),
                    Thread.ofPlatform().name("shared-2").start(HotSpots::updateShared),
                    Thread.ofPlatform().name("shared-3").start(HotSpots::updateShared),
                    Thread.ofPlatform().name("shared-4").start(HotSpots::updateShared));
            Thread.sleep(3000);
            running.set(false);
            for (Thread t : threads) {
                t.join();
            }
            rec.stop();

            Path file = Files.createTempFile("hotspots", ".jfr");
            rec.dump(file);
            List<RecordedEvent> events = RecordingFile.readAllEvents(file);

            top("CPU samples by top frame (jdk.ExecutionSample)", events,
                    "jdk.ExecutionSample", e -> 1, "samples");
            top("CPU-time samples by top frame (jdk.CPUTimeSample)", events,
                    "jdk.CPUTimeSample", e -> 1, "samples");
            top("Allocation by top frame (jdk.ObjectAllocationSample)", events,
                    "jdk.ObjectAllocationSample", e -> e.getLong("weight") >> 20, "MB");
            top("Lock waits by top frame (jdk.JavaMonitorEnter)", events,
                    "jdk.JavaMonitorEnter", e -> e.getDuration().toMillis(), "ms waited");
            Files.delete(file);
        }
    }

    interface Weight {
        long of(RecordedEvent e);
    }

    static String method(RecordedFrame f) {
        return f.getMethod().getType().getName() + "." + f.getMethod().getName();
    }

    static void byCaller(String top, String caller, Map<String, Long> map, long w) {
        map.merge(top + " <- " + caller, w, Long::sum);
    }

    // Groups events by the method at the top of the stack, like a profiler's "top" view
    static void top(String title, List<RecordedEvent> events, String type, Weight w,
                    String unit) {
        Map<String, Long> byFrame = new HashMap<>();
        long total = 0;
        for (RecordedEvent e : events) {
            if (!e.getEventType().getName().equals(type) || e.getStackTrace() == null) {
                continue;
            }
            List<RecordedFrame> frames = e.getStackTrace().getFrames();
            String name = method(frames.get(0));
            if (!name.startsWith("HotSpots.")) {          // JDK code on top: add our caller
                frames.stream().map(HotSpots::method).filter(m -> m.startsWith("HotSpots."))
                        .findFirst().ifPresent(m -> byCaller(name, m, byFrame, w.of(e)));
                total += w.of(e);
                continue;
            }
            byFrame.merge(name, w.of(e), Long::sum);
            total += w.of(e);
        }
        System.out.println(title + ", total " + total + " " + unit);
        long all = total;
        byFrame.entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .filter(en -> en.getValue() > 0)
                .limit(4)
                .forEach(en -> System.out.printf("  %6d %5.1f%%  %s%n", en.getValue(),
                        100.0 * en.getValue() / Math.max(1, all), en.getKey()));
    }
}

Output on a 2-CPU machine with JDK 25:

Output
CPU samples by top frame (jdk.ExecutionSample), total 453 samples
     204  45.0%  HotSpots.updateShared
     136  30.0%  HotSpots.isPrime
      99  21.9%  java.lang.Integer.formatUnsignedInt <- HotSpots.label
       7   1.5%  jdk.internal.util.DecimalDigits.uncheckedGetCharsLatin1 <- HotSpots.label
CPU-time samples by top frame (jdk.CPUTimeSample), total 576 samples
     237  41.1%  HotSpots.updateShared
     162  28.1%  HotSpots.isPrime
     138  24.0%  java.lang.Integer.formatUnsignedInt <- HotSpots.label
      30   5.2%  jdk.internal.util.DecimalDigits.uncheckedGetCharsLatin1 <- HotSpots.label
Allocation by top frame (jdk.ObjectAllocationSample), total 3280 MB
    3269  99.7%  jdk.internal.misc.Unsafe.allocateUninitializedArray <- HotSpots.label
      11   0.3%  java.lang.Thread.ofPlatform <- HotSpots.main
Lock waits by top frame (jdk.JavaMonitorEnter), total 7512 ms waited
    7512 100.0%  HotSpots.updateShared

What the four tables show:

  1. CPU (ExecutionSample): updateShared takes a large share, comparable to or larger than either intended hot spot, which may be surprising for a lock problem. The exact ranking of the three changes from run to run on a busy machine. The thread that holds the lock spins for 5 ms, and spinning uses CPU. The three threads waiting for the lock are blocked and use none, so a CPU profile cannot show the waiting at all. isPrime is one of the intended hot spots. The string work shows up under JDK methods such as Integer.formatUnsignedInt; the program adds the first application frame (<- HotSpots.label) because a top frame alone would hide who called it. A flame graph shows this without extra work.
  2. CPU time (CPUTimeSample): the same three methods, with more samples. This is JFR's CPU-time sampler from JEP 509, new and experimental in JDK 25 and Linux only. With 2 CPUs busy for about 3 seconds at one sample per 10 ms of CPU time, the upper limit is about 600 samples, and it came close. The older ExecutionSample event only samples threads running Java code, and only some of them in each period, which JEP 509 lists as its reasons for adding the new event.
  3. Allocation: almost all bytes come from label, attributed to a JDK internal array allocation (the string's byte array). The total is an estimate: each sample carries the bytes allocated since the previous one, so summing the weights approximates all allocation. The main row is the program's own setup.
  4. Lock waits: all of it is in updateShared. Three waiting threads for about 3 seconds can wait at most about 9 seconds in total; the reported total is below that because waits shorter than the 1 ms threshold and the start-up period are not counted.

The same recording can be made without code: java -XX:StartFlightRecording=duration=30s,filename=app.jfr -jar app.jar, or jcmd PID JFR.start for a running process, and then viewed with jfr print, JDK Mission Control or IntelliJ IDEA. async-profiler's jfrconv can turn a JFR file into a flame graph.

async-profiler or JFR

Choosing between them
NeedBetter fitWhy
Native, JVM-internal and kernel frames in one CPU profileasync-profilerperf_events integration; JFR shows Java frames
A flame graph in one commandasync-profilerHTML output built in
Hardware counters such as cache missesasync-profilerperf events like -e cache-misses
Native memory leaksasync-profilernativemem with leak analysis
Always-on recording in production with nothing extra to installJFRPart of the JDK; also records GC, JIT, I/O and thread events
Restricted environments where native agents are not allowedJFRNo native library to load

They also work together: --jfrsync writes async-profiler's samples into a normal JFR recording. For comparing two pieces of code rather than profiling an application, use a benchmark harness; see the JMH page. For GC behavior, see the GC deep dive.