Video in progress
A Java service is pinning one core at 100%. How do you find which thread and which code is to blame?
At the OS level you find the native thread ID using the most CPU, convert it to hex, match it with the nid in the thread dump and look at the stack. Taking several dumps and comparing them, or async-profiler, makes this more reliable.
📖 Answer
The classic manual method:
top -H -p <pid> # CPU per thread, the TID of the top one, for example 28417
printf '%x\n' 28417 # 6f01
jcmd <pid> Thread.print > td1.txt
grep -A 30 'nid=0x6f01' td1.txt
In the thread dump, each thread's nid field is exactly the OS thread ID in hex.
The result can be of two kinds:
- An application thread (
http-nio-8080-exec-12): an infinite loop in the stack, regex backtracking, sorting a huge collection. A single dump can lie, so take 3 dumps 5-10 seconds apart. If it is the same code every time, that is the culprit. - A JVM thread:
GC Thread#0,G1 Conc#0orC2 CompilerThread0. If it is the GC, the problem is in the heap: open the GC log, probably consecutive Full GCs. If it is C2, it is warm-up or a deopt cycle.
A better way is async-profiler:
asprof -d 30 -e cpu -f /tmp/cpu.html <pid>
The flame graph shows which methods ate the CPU over 30 seconds, along with JVM internal threads and native code. Unlike a thread dump, it samples at any point, not only at safepoints.
If top -H isn't available in the container, you can also get it from ps -L -o tid,pcpu -p <pid> or /proc/<pid>/task/*/stat. JFR's jdk.ThreadCPULoad event also gives CPU per thread.
Sign up to mark studied questions and save your progress.