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.
Contents
About this page
The asprofasprof
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 AsyncGetCallTraceperf_events
Why the "not only at safepoints" part matters: profilers built on standard JVMTI calls such as GetAllStackTraces
| Item | Value |
|---|---|
| Current stable release | 4.6, tagged October 2026 (4.5 was July 2026) |
| Official builds | Linux x64 and arm64 (.tar.gz.zip |
| Tools in the package | asproflibasyncProfiler.sojfrconv |
| Output formats | flamegraphtreecollapsedjfrotlp |
| Java API | Maven 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:
# 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:
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-agentpath
asprof
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:
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 jpsjps.html-fasprof
--- 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.isPrimeprimesThread__do_softirqperf_events
To profile from the moment the JVM starts, load the agent directly:
java -agentpath:/path/to/libasyncProfiler.so=start,event=cpu,file=profile.html -jar app.jar
CPU sampling engines and containers
-e cpu
| Engine | Mechanism | Kernel stacks | Works in containers by default | Notes |
|---|---|---|---|---|
cpu | One perf_event per thread, a signal every N ns of CPU time | Yes | No | Most accurate; uses one file descriptor per thread, so a low ulimit -n |
ctimer | timer_create | No | Yes | Linux only; resolution limited by the kernel tick (10 ms at HZ=100, 4 ms at HZ=250) |
itimer | setitimer(ITIMER_PROF) | No | Yes | One signal per process at a time, uneven between threads; the engine used on macOS |
With -e cpuperf_event_paranoidctimer
To get full CPU profiles in Docker, the guide gives three choices: relax seccomp (--security-opt seccomp=unconfined--cap-add SYS_ADMINasprof--fdtransfer-e ctimer
Profiling modes
| Event | Samples | What the top frame and counter mean | Example |
|---|---|---|---|
cpu | Threads using CPU, every 10 ms of CPU time by default | The method running; counter is CPU time | asprof -e cpu -i 5ms -d 30 -f cpu.html PID |
wall | All threads equally, running or not, every interval of real time | Where each thread is, including sleeping and blocked | asprof -e wall -t -i 50ms -f wall.html PID |
alloc | Heap allocations, through HotSpot TLAB callbacks | The class of the allocated object; counter is bytes | asprof -e alloc --alloc 500k -d 30 -f alloc.html PID |
lock | Contended Java monitors and java.util.concurrent | The class of the lock; counter is nanoseconds spent waiting to enter it | asprof -e lock -t -i 5ms -f lock.html PID |
nativemem | mallocrealloccallocfree | Allocations without a matching free (with jfrconv --leak | asprof start -e nativemem -f app.jfr PID |
ClassName.methodName | Every call of one Java method | Who calls it | asprof -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:
takes one sample per 500 KB allocated on average.--alloc 500k - Wall-clock mode is most useful with
, which splits the graph per thread. Without it, thousands of idle pool threads waiting on a queue can fill the graph. In 4.6,-t and--ithread include or exclude threads by name pattern, for example--xthread .--ithread 'http-*' - Several events at once need JFR output:
.asprof -e cpu --alloc 2m --lock 10ms -f profile.jfr PID also starts a normal JFR recording, so GC and other JVM events land in the same file, with execution samples from async-profiler.--jfrsync profile - Instrumenting a Java method (
) 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.-e ClassName.methodName
Options that changed
Many guides were written for version 2 or 3. These changes from the 4.6 changelog break commands copied from them:
| Before | In 4.6 |
|---|---|
--filter "http-nio*" | filter--ithread 'http-nio*'--xthread |
| Embedded HTTP server | Removed |
| macOS 10.x | macOS 11 or later |
Version 4.6 also added sending profiles straight to an OpenTelemetry endpoint, a rate limiter for JFR events (--ratelimit
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
- 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.
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:
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:
- CPU (ExecutionSample):
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.updateShared is one of the intended hot spots. The string work shows up under JDK methods such asisPrime ; the program adds the first application frame (Integer.formatUnsignedInt ) because a top frame alone would hide who called it. A flame graph shows this without extra work.<- HotSpots.label - 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.
- Allocation: almost all bytes come from
, 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. Thelabel row is the program's own setup.main - Lock waits: all of it is in
. 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.updateShared
The same recording can be made without code: java -XX:StartFlightRecording=duration=30s,filename=app.jfr -jar app.jarjcmd PID JFR.startjfr printjfrconv
async-profiler or JFR
| Need | Better fit | Why |
|---|---|---|
| Native, JVM-internal and kernel frames in one CPU profile | async-profiler | perf_events integration; JFR shows Java frames |
| A flame graph in one command | async-profiler | HTML output built in |
| Hardware counters such as cache misses | async-profiler | perf events like -e cache-misses |
| Native memory leaks | async-profiler | nativemem |
| Always-on recording in production with nothing extra to install | JFR | Part of the JDK; also records GC, JIT, I/O and thread events |
| Restricted environments where native agents are not allowed | JFR | No native library to load |
They also work together: --jfrsync