Video in progress
In prod a Java service is eating 100% CPU. How do you find which thread and which code is to blame?
First I get the IDs of the threads using the most CPU at the OS level (top -H), convert them to hex and match them with nid in a thread dump. A few dumps, or async-profiler's CPU flame graph, will show the exact method.
📖 Answer
The steps on Linux:
top -H -p <pid> # CPU per thread, take the TID at the top
printf '%x\n' 12873 # 12873 -> 3249
jcmd <pid> Thread.print > dump.txt
grep -A 20 'nid=0x3249' dump.txt
In the dump you'll see something like this:
"http-nio-8080-exec-17" ... nid=0x3249 runnable
java.lang.Thread.State: RUNNABLE
at java.util.regex.Pattern$Loop.match(...)
at com.shop.ValidationService.isValidEmail(...)
One dump is one moment in time. Take 3 to 5 dumps, and if that thread is always sitting in the same place, you've found the culprit.
Common causes:
- a regex with catastrophic backtracking (on a long string entered by a user);
- an infinite loop: a wrong
whilecondition, or parallel writes to aHashMapon an old JDK; - a livelock or a CAS retry loop that never ends;
- actually GC: if the hottest threads have names like
GC Thread#0orG1 Conc#0, the problem is in memory, not in the code. The GC log orjstat -gcutil <pid> 1000will confirm it.
For a more precise picture, use a profiler:
asprof -e cpu -d 30 -f cpu.html <pid>
A flame graph shows where CPU time goes at the method level and doesn't depend on a single moment. JFR works too (jcmd <pid> JFR.start duration=60s filename=cpu.jfr) and is safe in prod.
If top isn't available in the container, you can see per-thread CPU with ps -L -o tid,pcpu -p <pid>, or just start with JFR.
Sign up to mark studied questions and save your progress.