What you'll learn: By the end of this lesson you will be able to explain what a sampling profiler measures and what it cannot, start a Java Flight Recorder recording with the JDK's own tools, define your own event and gate its cost with
shouldCommit(), read a recording back in code, say what async-profiler adds (native and kernel frames, wall-clock, allocation and lock modes, flame graphs) and what it needs, and choose between them for a service that burns CPU.
A fitness tracker does not film your day. Every so often it checks your pulse, and after a week the readings say when you were resting and when you were running. A profiler works the same way: every few milliseconds it looks at what a thread is doing, and after enough looks the pile of readings shows where the time goes. The alternative is to guess, and engineers who guess usually optimise the code they understand, not the code that is slow.
This lesson builds on the garbage collector lesson, which ended with "read the evidence before you change a flag". Profiling is how you get that evidence when the symptom is CPU, not a pause. The companion topic of how queues turn slow code into slow requests is the planned lesson on Little's law and queueing, and the tail-latency lesson after it; both are named here in plain text because they are not published yet.
The lab ran on Java 25 with the JDK's own jdk.jfr module. async-profiler is described from its documentation and was not run.
The core idea
A sampling profiler takes periodic snapshots of thread stacks and counts them. The methods that appear in many snapshots are where the time goes, with statistical error. The JDK includes one, Java Flight Recorder (JFR). An external one, async-profiler, takes its samples differently and can see more.
Three illustrations run through the lesson:
- Minimal example: the lab, a thread spinning in one method, a recording read back in code.
- Realistic example: ShopStream's checkout service, whose CPU rises after a release, in "In practice".
- Failure example: a profile that points at the wrong place, because of where samples can be taken.
What JFR is and how to start it
The jdk.jfr package documentation says Flight Recorder "collects data as events", and that an event "has a time stamp, duration and usually an application-specific payload". Events come from the JVM (garbage collections, locks, compilation), from the operating system, and from your own code. The Flight Recorder API guide adds that you can correlate your own events with JVM events such as garbage collection or thread contention.
JFR has two bundled configurations, default.jfc and profile.jfc, in lib/jfr of the JDK. The guide says default "is recommended for continuous recordings" and gives "a good balance between data and performance (typically, less than 1% overhead)", while profile "records more events and is useful while profiling an application". The java command documentation says the same in operational terms: use profile "for short periods of time when more information is needed".
| Task | How |
|---|---|
| Start with the process | java -XX:StartFlightRecording:filename=rec.jfr,dumponexit=true,settings=profile ... |
| Start in a running JVM | jcmd <pid> JFR.start name=r1 duration=60s filename=rec.jfr settings=profile |
| Dump while it runs | jcmd <pid> JFR.dump name=r1 filename=rec.jfr |
| Summarise a file | jfr summary rec.jfr |
| Print events | jfr print --events jdk.ExecutionSample rec.jfr |
| Look at it in a GUI | JDK Mission Control |
The java documentation says -XX:StartFlightRecording "is equivalent to the JFR.start diagnostic command", and lists parameters such as duration, filename, maxage, maxsize and dumponexit. The jfr tool prints, summarises and aggregates recording files. Treat recordings as data that may hold secrets: the RecordingFile documentation says "Only recording files from trusted sources should be used", and jfr scrub exists to remove sensitive contents.
Figure 1. JFR is built into the JVM. How to read this: the service produces events at the settings you chose, a recording is written to a file, and tools read the file later, on another machine if you like. No agent is installed and nothing is attached.
How sampling turns stacks into a profile
When JFR samples Java threads it records a jdk.ExecutionSample event, whose stack trace is the call stack at that instant. RecordedEvent exposes it with getStackTrace(), and the sampled thread is a field of the event. In the bundled configurations the sample period differs: the lab below reads it out of the JDK and prints 20 ms for default and 10 ms for profile.
Figure 2. A profile is a pile of stacks. How to read this: the sampler never asks "how long did this method take". It asks "what is running now" many times, and the share of samples is the estimate of the share of time.
Two consequences follow. First, a share is an estimate: with few samples it is noisy, so a profile of a few seconds of an idle service says little. Second, where a sample can be taken matters. Nitsan Wakart's analysis of Java profilers describes safepoint bias: a profiler that can only sample at safepoint polls reports the nearby poll location, not where the code ran, because after compilation polls sit mainly at method exits and loop back edges. async-profiler states that it "does not suffer from the Safepoint bias problem". For JFR, do not assume either way: compare with a second tool before you trust a surprising frame.
Build it: record, read back, find the hot method
This is the minimal example: JFR used as a library from inside a program, with output that contains no time.
Goal. Commit an event of your own, let the sampler watch a busy thread, dump the recording to a file and read the file back.
Setup. From examples/backend:
./gradlew :labs:jfr-recording-readback:check --console=plain
./gradlew -q :labs:jfr-recording-readback:run
The first command runs 5 tests; the second prints the output below. The code is in examples/backend/labs/jfr-recording-readback/src/main/java/buildingai/labs/jfrreadback/.
How it works. A custom event is a subclass of Event with fields; the pattern from the jdk.jfr documentation is to populate it and call commit(), with shouldCommit() to skip expensive work when no recording wants the event:
@Name("buildingai.OrderPriced")
@Label("Order priced")
public class OrderPriced extends Event {
@Label("Line items") public int lineItems;
@Label("Pricing route") public String route;
}
// in the code being measured
OrderPriced event = new OrderPriced();
event.begin();
// ... the work being measured ...
event.end();
if (event.shouldCommit()) { // false when disabled or under its threshold
event.lineItems = items; // payload built only when somebody records it
event.route = "standard";
event.commit();
}
The recording side creates a Recording, enables the events it wants, starts it, and dumps it to a file; RecordingFile.readAllEvents reads the file back as RecordedEvent objects whose getStackTrace() gives the stack and whose sampledThread field names the thread. Experiment 2 runs a thread named profiled-worker in Work.hotLoop while jdk.ExecutionSample is enabled at 10 ms, and polls until at least 20 samples of that thread exist, so a busy machine still passes. Nothing about how many samples there were is printed.
Expected output, captured from a real run (Java 25):
Experiment 1: an application event, recorded to a file and read back with RecordingFile
recording setting: enabled events read back: 5 sum of lineItems: 15 payloads built: 5
recording setting: disabled events read back: 0 sum of lineItems: 0 payloads built: 0
recording setting: unset events read back: 5 sum of lineItems: 15 payloads built: 5
Experiment 2: the sampler finds a hot method (thread "profiled-worker" runs Work.hotLoop, jdk.ExecutionSample every 10 ms)
at least 20 samples of that thread: yes
every sample has a stack trace with frames: yes
most common top frame: buildingai.labs.jfrreadback.Work.hotLoop
Work.hotLoop on the stack of most samples: yes
Experiment 3: the JDK's bundled configurations (read from the JDK, not measured)
default jdk.ExecutionSample#period = 20 ms
profile jdk.ExecutionSample#period = 10 ms
What the output shows. Experiment 1: with the event enabled, five events come back and the line items sum to 15 (1+2+3+4+5), and the payload was built five times. With the event disabled by the recording, zero events come back and the payload was built zero times: shouldCommit() returned false, so the work to fill the event never ran. With no setting at all the event is recorded, because the Event documentation says an event is enabled by default. Experiment 2: every sample has frames, the most common top frame is Work.hotLoop, and hotLoop is on the stack of most samples. That is what a profiler reports for one busy thread. Experiment 3 reads two settings out of the JDK, and the numbers are the bundled configuration's, not a measurement.
Break it. Add a second CPU-bound method that runs a tenth as often and see what the sampler can and cannot say about the ratio. Change the period to one second and see how long 20 samples take.
Stretch. Write the file to a fixed path and read it with jfr summary and jfr print --events jdk.ExecutionSample. Replace the polling loop with RecordingStream.
What the model leaves out. Overhead measurement, native and kernel frames, other events, and any other JVM than the one that ran it. A single busy thread is the easiest case for a sampler.
async-profiler: what it adds, and what it costs
async-profiler is an open-source sampling profiler for Java. Its README describes it as combining AsyncGetCallTrace and perf_events, and says it "monitors non-Java threads (e.g., GC and JIT compiler threads) and shows native and kernel frames in stack traces". It runs as an agent inside the target process, controlled with the asprof tool, and it is officially maintained for Linux and macOS (the README lists Linux x64 and arm64 and macOS x64 and arm64).
Its profiling modes, from its documentation:
| Mode | Option | What it answers |
|---|---|---|
| CPU | default | Which Java, native, JVM and kernel code is on a CPU |
| Wall clock | -e wall |
Where threads are, "regardless of thread status: Running, Sleeping or Blocked" |
| Allocation | -e alloc |
Which call paths allocate; the top frame is the class allocated |
| Locks | -e lock |
Where threads contend for monitors |
Typical commands from its Getting Started page:
asprof start 8983 # start profiling the process with id 8983
asprof stop 8983 # stop and print the result
asprof -d 30 -f flamegraph.html 8983 # profile for 30 seconds, write a flame graph
These were not run for this lesson: they need Linux or macOS and a target process, and no output from them appears here. The documentation lists requirements that matter in production. For kernel stacks without root, perf_event_paranoid and kptr_restrict must be set (the Getting Started page gives 1 and 0), and in a container the Troubleshooting page warns that seccomp can disable perf_event_open, with -e ctimer as the fallback that needs no perf events but gives no kernel stacks. For accuracy it recommends starting the JVM with -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints.
The output is usually a flame graph: the documentation calls it "a hierarchical representation of call traces of the profiled software". Width is the share of samples, the stack grows upward, and a wide plateau at the top is code that is on the CPU itself. async-profiler can also write the JFR format, which the same documentation says JDK Mission Control and IntelliJ IDEA can open.
Figure 3. Match the mode to the symptom. How to read this: CPU samples show code that was running, so they cannot explain a service that is slow because its threads wait. Wall-clock and lock modes answer that.
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
JFR, default always on |
Low overhead, history for after-the-fact analysis | Coarser sampling | You need to see native code |
JFR, profile for a window |
More events, same tooling | More overhead, per its documentation | Left on continuously |
| async-profiler | Native and kernel frames, wall, alloc and lock modes | Attach and kernel settings; Linux and macOS | You cannot change container or kernel settings |
| Custom JFR events | Business meaning (an order was priced) | You write and maintain them | The event fires millions of times with no gate |
| Guessing | Free | Wrong place, often | Always |
In practice: ShopStream's checkout after a release
This is the realistic example, an educational scenario on ShopStream; nothing in it describes a real company. Every figure is illustrative.
This is a realistic scenario, not a case history.
The situation
After a release, the pricing step of ShopStream's checkout service uses noticeably more CPU at the same request rate, and its latency rises at peak. The release changed several things. Nobody can say which.
Starting architecture
Figure 4. Always-on history, on-demand depth. How to read this: the low-overhead recording runs all the time so a past incident can be studied; the heavier, deeper profile is taken for a short window on one instance.
Options considered
| Option | What it does | Risk |
|---|---|---|
| A. Revert the release | Restores CPU | Loses the release's features and teaches nothing |
| B. Scale out | More instances | Pays for the problem every day |
| C. Profile one instance under load, compare with the previous version | Names the method | Needs a comparable load and a second profile |
The decision
Option C. Profile one canary of the old version and one of the new at the same traffic share, with the same tool and the same window, and compare the widest frames.
Rollout and verification
Each canary gets a 30 second profile at peak. The comparison is the share of samples per top method, not wall-clock figures. A method that is wide only in the new build is the suspect. The fix is verified the same way: a third profile on the canary with the fix, and the CPU graph for that instance.
The 2 a.m. failure
The page reads: CPU is high again, and the profile of the new instance shows a wide frame in the JSON serializer, which no one touched. A wall-clock profile taken next shows many threads waiting on a lock in the price cache. The serializer was where the running threads happened to be, not the cause: the cache lock held requests back, and the CPU profile could not show the waiting. The checks: take a wall-clock or lock profile as well as a CPU profile, compare the top frames of both, and look for the lock owner. The mitigation is to shed load and restart the instance; the lasting fix is to remove the contention and add a custom JFR event around the cache fill so the next page shows how long requests waited.
Architect's notes
- Keep a low-overhead recording on, so the evidence exists when the page comes at 2 a.m.
- A profile answers "where", not "why". Read the code around the wide frame.
- Compare profiles, do not read one in isolation. Same load, same window, old build and new build.
- CPU and wall-clock profiles answer different questions. Take both when latency rises without CPU.
- Guard custom events with
shouldCommit()so an event on a hot path costs almost nothing when nobody records it. - Treat
.jfrfiles as sensitive. They can contain stack traces and event payloads.
Common mistakes
- Reading a few seconds of samples and trusting the percentages.
- Profiling a cold JVM that has not warmed up, then optimising code that will be compiled.
- Reading CPU samples as the cause of slow requests when threads are waiting.
- Left-on
profilesettings in production, against the documentation's advice. - Trusting one tool's surprising frame without a second look.
- Attaching async-profiler in a container without checking
perf_event_openis allowed.
Key takeaways
- A sampling profiler counts stack snapshots; shares are estimates and need enough samples.
- JFR ships with the JDK, has a documented low-overhead default and a heavier
profileconfiguration, and can be started with-XX:StartFlightRecordingorjcmd JFR.start. - Custom events carry business meaning;
shouldCommit()keeps them cheap when nobody records them. - async-profiler adds native and kernel frames and wall-clock, allocation and lock modes, and needs Linux or macOS plus kernel settings.
- Compare two profiles taken at the same load before you change code.
Practice exercises
Exercise 1 (20 min). Run the lab and read each line of the output. For each line say whether it is something the program controls or something the JVM decided.
Exercise 2 (45 min). Add OrderPriced events to a copy of the lab with a @Threshold and describe when shouldCommit() returns false.
Exercise 3 (1 hour). Start any JVM program with -XX:StartFlightRecording:filename=rec.jfr,dumponexit=true,settings=profile, then run jfr summary rec.jfr and jfr print --events jdk.ExecutionSample rec.jfr. Name the three widest top frames.
Exercise 4 (2 hours). For ShopStream's search, checkout and image services, choose which to leave a recording on for, which to profile on demand, and what result would make you reach for async-profiler.
Related reading
- Garbage Collectors: G1 and ZGC: the GC side of the same JVM, and the log you read before you change a flag.
- The JVM Memory Model and Heap: what the allocation profile is about.
- Thread Pools, Executors and CompletableFuture: the threads a wall-clock profile shows waiting.
- Latency vs Throughput: why a slow method becomes a slow request.
- Observability and SLOs: the dashboards that tell you a profile is needed.
Official documentation
- Oracle, Package
jdk.jfr, Java SE 25 API andEvent. - Oracle, Flight Recorder API Programmer's Guide: Flight Recorder Configurations.
- Oracle, The
javacommand,jcmdandjfr. - async-profiler, README and its profiling modes.
- Nitsan Wakart, a 2016 blog post on why most sampling Java profilers are biased, on safepoint bias.