Sub topic 10
Reading flame graphs
This chapter assumes you can record a JFR file, you know what a stack trace is, and you have seen a CPU profile as a table of hot methods. A flame graph shows the same samples as a picture. You will learn what each part of the picture means, how to build one from a JFR recording, and which mistakes lead people to wrong conclusions.
What a flame graph shows
A CPU profiler takes samples. Each sample is a stack trace: the chain of method calls on a thread at one moment. A flame graph merges thousands of these stacks into one picture.
- Each rectangle is a method (a stack frame).
- The vertical axis is stack depth. The bottom is the root, such as
mainor a thread'srun. Callees sit on top of their callers. - The width of a rectangle is the share of samples in which that method appeared anywhere in the stack.
- The horizontal axis is not time. Rectangles at the same level are usually sorted alphabetically so identical stacks merge. Left to right does not mean earlier to later.
- Color is usually decoration. In most tools it only separates neighbors, or it marks the kind of code (Java, native, kernel).
An icicle graph is the same chart flipped, with the root at the top. JDK Mission Control draws it this way. The reading rules are identical.
In a flame graph, Slow.main would be a full-width bar at the bottom. The concatenation bar above it would cover 90% of that width. Arrays.copyOf would sit on top of it with 70%.
Self time and total time
Every rectangle has two numbers. Total time is its full width, which includes everything it calls. Self time is the part of the width not covered by rectangles above it. That is time spent in the method's own code.
Slow.main has a total of 100% but a self time of 8%. Its hot path is the one that leads to Arrays.copyOf. Reading a flame graph means finding where self time concentrates.
- Start at the top edge of the graph. Find the widest plateaus, which are frames with little or nothing above them. These are where the CPU was actually executing.
- Compare each plateau's width to the whole graph, not to its neighbors. A plateau that is 3% wide is not worth a rewrite, however tall its tower is.
- Walk down from a wide plateau to see who called it. This tells you which of your own methods to change. The top frame is often JDK code such as
Arrays.copyOf, and you cannot change it. Look for the lowest frame of your own code under it. - Look at wide bars in the middle that have several different children. These are good places to cut work. Calling the method less often reduces everything above it.
Tall towers are not a problem by themselves. Depth only reflects deep call chains, which are common in frameworks. Width is what costs time.
Building a flame graph from a JFR file
JMC can display a flame graph directly. Outside JMC, the usual input is a folded stack file. It has one line per distinct stack, with frames separated by semicolons from root to leaf, followed by a sample count. The program below reads jdk.ExecutionSample events from a recording and prints that format.
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordedFrame;
import jdk.jfr.consumer.RecordedStackTrace;
import jdk.jfr.consumer.RecordingFile;
public class Fold {
public static void main(String[] args) throws Exception {
Map<String, Long> counts = new TreeMap<>();
for (RecordedEvent e : RecordingFile.readAllEvents(Path.of(args[0]))) {
if (!e.getEventType().getName().equals("jdk.ExecutionSample")) {
continue;
}
RecordedStackTrace trace = e.getStackTrace();
if (trace == null) {
continue;
}
var frames = trace.getFrames();
StringBuilder sb = new StringBuilder();
for (int i = frames.size() - 1; i >= 0; i--) {
RecordedFrame f = frames.get(i);
if (sb.length() > 0) {
sb.append(';');
}
sb.append(f.getMethod().getType().getName())
.append('.')
.append(f.getMethod().getName());
}
counts.merge(sb.toString(), 1L, Long::sum);
}
counts.forEach((stack, n) -> System.out.println(stack + " " + n));
}
}Record the Slow program and fold it. Then feed the result to Brendan Gregg's flamegraph.pl script, which writes an SVG you can open in a browser.
java -XX:StartFlightRecording=filename=slow.jfr,settings=profile Slow
java Fold.java slow.jfr > folded.txt
flamegraph.pl folded.txt > slow.svgThe SVG is interactive. Click a rectangle to zoom into it. Use the search box to highlight every frame that matches a name, such as your package prefix. The search also reports what percentage of samples contain a match.
Choosing what to measure
The same drawing can show different things, depending on which events you fold.
| Event source | Width means | Use it for |
|---|---|---|
| `jdk.ExecutionSample` | Share of CPU samples | Finding code that burns CPU |
| `jdk.ObjectAllocationSample` | Share of sampled allocation weight | Finding code that creates garbage |
| `jdk.JavaMonitorEnter` | Share of time blocked on monitors | Finding lock contention |
| Wall-clock samples (for example async-profiler) | Share of elapsed time, including waiting | Finding slow I/O and waits |
A CPU flame graph never shows time spent waiting on a socket or a lock, because a waiting thread is not on the CPU. If your latency is high but the CPU graph looks flat and boring, the time is going somewhere else. Switch to a wall-clock or lock view.
Common misreadings
- Reading the x-axis as time. A wide bar on the left did not run first. If you need a timeline, use JMC's thread view.
- Treating a wide bar as a hot spot.
Thread.runandmainare always 100% wide because everything runs under them. Look at the top edge instead. - Trusting tiny differences. A profile with 400 samples has large statistical noise. The default JFR sampling period is 10 or 20 milliseconds, so a 60-second recording of one thread yields only about 3,000 to 6,000 samples. A 2% bar is within noise. Record longer or use more load before reading small features.
- Ignoring truncated stacks. JFR keeps 64 frames by default (
stackdepth). Deep frameworks may lose the root, so identical bottoms look different and the graph fragments. Raisestackdepthif bars seem split strangely. - Forgetting inlining. The JIT compiler merges small methods into their callers. JFR reconstructs the logical frames from debug information, so inlined methods usually still appear. Tools that read raw native frames may not show them.
- Comparing graphs by absolute width. Two graphs from runs of different length cannot be compared by sample count. Compare percentages, or use a differential flame graph, which colors frames by how much their share grew or shrank between two runs.
Profilers also differ in how accurately they place samples. The earlier chapter on safepoint bias explains why some tools attribute time to the wrong frame. JFR does not suffer from it in the same way, but treat any tool's top frames with some skepticism.
A short reading routine
- Check the sample count and the duration. If either is small, record again.
- Confirm the graph reflects the load you care about, not startup.
- Find the three widest top-edge plateaus.
- For each, walk down to the lowest frame in your own code.
- Write a hypothesis, make one change, and record a new graph to compare.
Exercise
In a CPU flame graph, OrderService.process is a bar covering 60% of the width. Directly above it, JsonWriter.write covers 55% and nothing sits on top of JsonWriter.write except a narrow String.format bar at 5%. What are the total and self times of OrderService.process, and which method should you investigate first?
Show answer
OrderService.process has a total of 60%. Its self time is 60% minus the 55% covered by JsonWriter.write, which is about 5%. JsonWriter.write has a total of 55% and a self time of about 50% (55% minus the 5% in String.format). Investigate JsonWriter.write first, because the self time concentrates there.
Exercise
Your service has slow responses, but its CPU flame graph is small and flat, with no wide plateau. Name one likely reason and one view you could try next.
Show answer
The threads are probably waiting (on I/O, a lock, or a downstream service), and a waiting thread does not appear in CPU samples. Try a wall-clock flame graph, or fold jdk.JavaMonitorEnter events to see lock waits.