Video in progress

In prod a service's CPU hits 100% and doesn't come down. How do you find which thread and which code is eating the CPU without a restart?

First I separate whether GC or application code is eating the CPU, using GC metrics. Then I find the thread IDs using the most CPU with top -H and match them to the nid in a thread dump, or I take a 30-60 second CPU profile directly with async-profiler/JFR and look at the hot method in the flame graph.

📖 Answer

The first question: is it GC? If rate(jvm_gc_pause_seconds_sum[1m]) is high and the old gen is full, GC threads are eating the CPU, and the cause is memory. Then you need heap analysis, not a profile. If GC is normal, it is application code.

A quick way, with no extra tools:

top -H -p <pid>                  # threads using the most CPU, for example TID 4123
printf '%x\n' 4123               # 101b
jcmd <pid> Thread.print | grep -A 20 'nid=0x101b'

Repeat it 2-3 times, and if you see the same stack, you've found it. Often it is an infinite loop, sorting a huge collection over and over, a regex with catastrophic backtracking, or a corrupted structure from modifying a HashMap in parallel without synchronization.

A more precise way is a sampling profiler:

# async-profiler, 60-second CPU profile
asprof -d 60 -e cpu -f /tmp/cpu.html <pid>

# or JFR built into the JDK
jcmd <pid> JFR.start duration=60s filename=/tmp/cpu.jfr settings=profile

In the flame graph, the widest "plateau" is where the time goes. If async-profiler has no perf_event_paranoid permission in the container, the -e itimer mode works; JFR doesn't ask for any permission.

What to do right away once you've found it depends on the cause. If it is a regex or one specific request type, turning that path off with a rate limit or feature flag is faster and safer than a restart. Once the evidence (dumps, profile) is collected, restart if needed.

For next time: continuous profiling, or at least a script that takes a JFR dump automatically when CPU goes above 90%. If the problem happens at night, the evidence is ready in the morning.