Sub topic 8
Finding CPU hot spots
This chapter assumes you can run a Java program from the command line and read a stack trace. It also assumes you know what a recording in Java Flight Recorder (JFR) is and have a JDK 11 or later. The chapter on JFR covers recording in more depth. Here you use a recording to answer one question: which methods are burning CPU?
What a CPU profile measures
A CPU profile is a statistical summary of where your Java threads were running code. JFR does not time every method call. The event jdk.ExecutionSample fires about every 10 or 20 ms, depending on the settings. At each tick JFR picks a few threads that are running Java code and records each one's stack trace. A method that appears in 30% of the samples probably accounts for about 30% of the CPU time spent in Java code.
Because this is sampling, two things follow:
- Results are estimates. A few dozen samples are not enough, and a few thousand are.
- Overhead is low and nearly independent of how many methods you call. That is why you can use it on realistic workloads.
A program with an obvious hot spot
Save this as Slow.java. It builds a string by repeated concatenation, which copies the whole string on every iteration.
public class Slow {
public static void main(String[] args) {
long start = System.nanoTime();
for (int round = 0; round < 200; round++) {
String s = "";
for (int i = 0; i < 5_000; i++) {
s += i;
}
if (s.length() == 0) {
System.out.println("unreachable");
}
}
System.out.println((System.nanoTime() - start) / 1_000_000 + " ms");
}
}Compile it and record a run. The profile settings sample more often than the default settings. JFR writes the file when the JVM exits.
javac Slow.java
java -XX:StartFlightRecording=filename=slow.jfr,settings=profile SlowNote the printed time. You need it as a baseline later.
Reading the samples
The jfr tool in the JDK can summarize the recording without a GUI. First check that you collected enough samples:
jfr summary slow.jfrLook for the jdk.ExecutionSample line in the output and read its count. Then print a few samples with short stacks:
jfr print --events jdk.ExecutionSample --stack-depth 4 slow.jfrEach event shows a thread and a stack, with the top frame first. On JDK 21 and later, jfr view hot-methods slow.jfr prints a ranked table directly.
For a visual view, open slow.jfr in JDK Mission Control (JMC). Go to the Java Application page, then Method Profiling. The Hot Methods table ranks methods by sample count. The Stack Trace view lets you group samples by top frame or by whole stack.
For Slow, the top frames are normally in the JDK's string-concatenation code and in array copying. The exact names depend on your JDK version. Your own Slow.main shows up one or two frames below. The profile is telling you that the time goes into copying characters, not into your arithmetic.
Self time and total time
Every method has two numbers:
| Measure | Counts a sample when the method is... | Answers the question |
|---|---|---|
| Self time (top frame) | the first frame of the stack | Where is the CPU actually spending cycles? |
| Total time (inclusive) | anywhere in the stack | Which part of my code is expensive, counting everything it calls? |
Self time points at the leaf, which is often a JDK method you cannot change. Total time points at the caller you can change. Use both: find the heaviest leaf, then walk down the stack to the nearest frame that is your code. In Slow, main has near-100% total time but almost no self time. The leaf frames hold the self time. The fix belongs in main.
Fixing and re-measuring
The repeated copying is the problem. A StringBuilder appends into a buffer that grows, so each character is copied only a few times in total.
public class Fast {
public static void main(String[] args) {
long start = System.nanoTime();
for (int round = 0; round < 200; round++) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5_000; i++) {
sb.append(i);
}
String s = sb.toString();
if (s.length() == 0) {
System.out.println("unreachable");
}
}
System.out.println((System.nanoTime() - start) / 1_000_000 + " ms");
}
}Record it the same way, with filename=fast.jfr, and compare both the printed time and the profile. Expect a much shorter run and far fewer samples. The remaining samples should sit in StringBuilder code rather than in the copying that dominated before. Compare sample counts only when the workload is the same. A shorter run has fewer samples simply because it ran for less time.
What the profile does not show
Most confusing results come from forgetting what jdk.ExecutionSample covers.
- Only threads running Java code. A thread blocked on a lock, sleeping, or waiting on I/O is not in these samples. A service that is slow while its CPU is idle will show an unhelpful CPU profile. Look at lock and I/O events, or at thread dumps, instead.
- Native code is sampled separately. Time spent inside native methods appears under
jdk.NativeMethodSample. If the JDK's own native frames matter, check that event too. - Inlining. The JIT compiler merges small methods into their callers. JFR still reports the logical Java frames, so you normally see the methods you wrote. Very hot code may be attributed to a different line than you expect.
- Warmup. Early samples include interpreted and not-yet-optimized code. For a long-running server, discard the first minute or so of the recording. For a short batch job, warmup may be a real part of the cost.
- Other JVM threads. The JIT compiler and the garbage collector use CPU in their own threads. A busy GC does not appear as hot Java methods. Check GC logs when total process CPU is high but the Java samples look modest.
- Not enough samples. If
jfr summaryshows only a handful of execution samples, record longer or raise the load. Do not draw conclusions from them.
Common errors
- Optimizing the top self-time frame when it is JDK code. Instead, change how your code calls it, as the
StringBuilderfix does. - Comparing two recordings with different workloads. Compare time per request or per operation, not raw sample counts.
- Changing several things at once. You cannot tell which change helped. Make one change, then record again.
- Treating one percentage as exact. A method at 12% and one at 14% are within noise of each other, so do not read much into the order.
Exercise
A profile shows Slow.main with 100% total time and 0% self time, and a JDK string method with 70% self time. Which method should you change, and why?
Show answer
Change Slow.main. The JDK method holds the self time, but you cannot edit it. Your code decides how often it is called and with what arguments, so the fix goes in the nearest frame you own, which is main.
Exercise
Users report that a service is slow, but a JFR recording shows few jdk.ExecutionSample events and the process CPU is low. What does that suggest, and what would you check next?
Show answer
The threads are mostly not running Java code. They are probably blocked, sleeping, or waiting on I/O or locks. Check thread dumps and JFR's lock and I/O events, such as monitor-blocked and socket read events, instead of the CPU profile.