Projects / Profiler agent / Phase 4
Phase 4 of 4 · about 2.5 hours
Flame graph, attach, and a cross-check
You end with a flame graph in a browser, a profile of a program that was already running, and a comparison against the JDK's own profiler.
Step 4.1: Draw a flame graph (about 40 minutes)
A table of numbers hides the shape of a program. A flame graph shows it. Each box is a method, boxes stacked upward are callers and callees, and the width of a box is the share of samples that contained it. A wide box low in the graph is a method that takes a lot of time, and what sits on top of it shows where that time goes. The x axis is not time: boxes are placed in alphabetical order so that identical stacks merge, which is why it is a "graph" and not a "chart".
Our version first builds a tree from the collapsed stacks, then writes one SVG rectangle per node:
/** Boxes are placed left to right in name order; a child sits one row above its parent. */
private static void draw(StringBuilder svg, Node node, int level, double x, int total, int height) {
double w = (double) node.count / total * WIDTH;
double y = height - (level + 1) * ROW;
String label = node.name + " (" + node.count + " samples, "
+ String.format("%.1f", 100.0 * node.count / total) + "%)";
svg.append(String.format("<g><title>%s</title><rect x=\"%.2f\" y=\"%.0f\" width=\"%.2f\" height=\"%d\" fill=\"%s\" stroke=\"#fff\"/>",
escape(label), x, y, w, ROW - 1, color(node.name)));
int chars = (int) (w / 6.6) - 1;
if (chars >= 3) {
String shown = node.name.length() <= chars ? node.name : node.name.substring(0, chars - 1) + "~";
svg.append(String.format("<text x=\"%.2f\" y=\"%.0f\" fill=\"#222\">%s</text>", x + 3, y + 12, escape(shown)));
}
svg.append("</g>\n");
double cx = x;
for (Node child : node.children.values()) {
draw(svg, child, level + 1, cx, total, height);
cx += (double) child.count / total * WIDTH;
}
}
Walk through it:
- The width of a node is
count / total * 1200, so the root is always the full width, and every child is a slice of its parent. - A child is drawn one row above its parent.
cxmoves to the right as we place the siblings. - Every box gets a
<title>, which browsers show as a tooltip when you hover over it. The text label is drawn only when the box is wide enough to hold a few characters. - The color comes from a hash of the method name, so a method has the same color in every run. That makes two graphs easy to compare by eye.
Switch it on with svg=flame.svg and open the file in a browser:
java -javaagent:agent.jar=mode=cpu,svg=flame.svg -cp work Workload
done true
prof: 278 samples
thread [main] 100.0%
total self method
100.0% 0.0% Workload.main
60.1% 60.1% Workload.hot
10
The last line is the number of boxes in the graph. At the bottom you see all and [main], then Workload.main, and above it three boxes side by side: cold at about a tenth of the width, hot at about six tenths, warm at about a third. On top of warm stand the StringBuilder frames that we could not see in Phase 1.
Step 4.2: Attach to a program that is already running (about 40 minutes)
A real service cannot always be restarted with a new flag. The JVM allows an agent to be loaded into a running process, through the Attach API. A small tool connects to the target by its process id and tells it "load this agent JAR". The target then calls agentmain, the twin of premain:
/** Runs when the JVM starts with -javaagent. We profile until the program exits. */
public static void premain(String args, Instrumentation inst) {
start(Options.parse(args));
}
/** Runs when Attach loads us into a JVM that is already running. */
public static void agentmain(String args, Instrumentation inst) {
Options options = Options.parse(args);
if (options.seconds() <= 0) {
System.err.println("prof: an attached profiler needs seconds=N, so it knows when to stop");
return;
}
start(options);
}
Because the target keeps running, we cannot wait for it to exit to write the report. An attached agent takes seconds=N, samples for that long, and then reports on its own. The start method does this with a timer thread. That is also why the manifest now has a second line:
Premain-Class: prof.Agent
Agent-Class: prof.Agent
Premain-Class is read when the agent starts with -javaagent, and Agent-Class when it is loaded later. Now the small tool that does the attaching:
package prof;
import com.sun.tools.attach.VirtualMachine;
/** Usage: java -cp out prof.Attach PID agent.jar "interval=10,seconds=3" */
public final class Attach {
private Attach() {}
public static void main(String[] args) throws Exception {
VirtualMachine vm = VirtualMachine.attach(args[0]);
try {
vm.loadAgent(args[1], args.length > 2 ? args[2] : "");
} finally {
vm.detach();
}
}
}
The script starts the workload for twelve seconds in the background, waits two seconds, attaches for three seconds, and waits for the program to end:
java -cp work Workload 12 &
PID=$!
sleep 2
java -cp out prof.Attach $PID agent.jar interval=10,seconds=3,out=live.collapsed
wait $PID
WARNING: A Java agent has been loaded dynamically (agent.jar)
WARNING: If a serviceability tool is in use, please run with -XX:+EnableDynamicAgentLoading to hide this warning
WARNING: If a serviceability tool is not in use, please run with -Djdk.instrument.traceUsage for more information
WARNING: Dynamic loading of agents will be disallowed by default in a future release
prof: 277 samples
thread [main] 100.0%
total self method
100.0% 0.0% Workload.main
59.9% 59.9% Workload.hot
30.3% 7.6% Workload.warm
22.7% 0.0% java.lang.AbstractStringBuilder.append
22.7% 22.4% java.lang.AbstractStringBuilder.ensureCapacityInternal
22.7% 0.0% java.lang.StringBuilder.append
9.7% 9.7% Workload.cold
0.4% 0.4% java.util.Arrays.copyOf
done true
The WARNING lines come from the JVM, which tells us that an agent was loaded dynamically. In JDK 21 that is only a message, and the JVM says that a future release will disallow it by default, so a program that must keep supporting attach will need to start with -XX:+EnableDynamicAgentLoading. Below the warning is our report, taken from three seconds in the middle of a program that was never started with our agent.
Step 4.3: Check it against the JDK's own profiler (about 40 minutes)
How do you know our profiler is not wrong in some way we cannot see? You hold it against another tool that works differently. The JDK ships Java Flight Recorder (JFR), a profiler built into the JVM. We record the same program with it, then read its method samples with the jfr tool:
java -XX:StartFlightRecording=filename=rec.jfr,settings=profile -cp work Workload > /dev/null 2>&1
jfr print --events jdk.ExecutionSample --stack-depth 1 rec.jfr \
| grep -E '^\s+[A-Za-z.$]+\.[A-Za-z]+\(' | sed -E 's/\(.*//; s/^ +//' \
| sort | uniq -c | sort -rn \
| awk '{n[$2]=$1; t+=$1} END {for (m in n) printf "%5.1f%% %s\n", 100*n[m]/t, m}' \
| sort -rn | head -5
The jfr print command prints the recorded events, and --stack-depth 1 keeps only the innermost frame of each sample, as in our Phase 1 report. Then a little shell turns the lines into percentages:
65.5% Workload.hot
10.9% java.lang.Integer.getChars
10.9% Workload.cold
6.4% Workload.warm
4.9% java.util.Arrays.copyOf
Put the two side by side. The numbers below come from our two runs of the same program:
| Method | Our sampler (Step 4.1 run) | JFR |
|---|---|---|
Workload.hot | about 60% | about 63% |
Workload.cold | about 10% | about 10% |
warm and its StringBuilder calls | about 30% | about 25% |
The order is the same and the big gap is the same: hot takes more than half. The few points of difference are what you expect from two samplers that take their samples in different ways. Neither agrees exactly with the 60/30/10 we built in, and we do not need them to. A profiler's job is to point at the right method, not to produce a number you can put in a contract.
Step 4.4: When not to trust it (about 30 minutes)
You have built a working profiler. Now the limits: where would it lead you astray?
- Safepoint bias. The JVM can only read a thread's stack when the thread is at a safepoint, a place in the code where it is safe to pause. Profilers built on this kind of stack walk see some places more often than others, because the code between safepoints is invisible to them. Our sampler is of this kind. JFR samples threads in a different way and is not tied to safepoints in the same manner, which is one reason to cross-check, as we did.
- Too few samples. Our runs have a few hundred samples. A method at 2% is a handful of samples, and you cannot tell it from noise. Run longer, or sample faster, before you act on a small number.
- Inlining. The JIT compiler folds small methods into their callers. The JVM can still tell us the original frames, as you saw with
StringBuilder.append, but the time you attribute to them is less exact than for a big method. - Observer effect. Taking a snapshot stops threads. Step 3.4 showed the cost in samples per second, and a busy production service pays it in latency.
- Only what Java can see. Time spent inside native code, in the garbage collector or in the JIT compiler is not in a Java stack trace. A profile that adds up to 100% may still hide a part of the story.
Pitfall: one profile is one opinion. Before you act on a hot method, compare it with a second profiler, as Step 4.3 does.
Always ask a second question. When the profile says "method X", can a second tool, or a small experiment, confirm it?