Video in progress

A Java service in a pod has pushed CPU to 100%. How do you find which thread is to blame?

With top -H -p <pid> I get the ID of the thread using the most CPU, convert it to hex, and match it against nid=0x... in the thread dump. That shows exactly which code is spinning.

📖 Answer

On Grafana, CPU is pinned at the limit and latency is up. Gather evidence before you restart, because after a restart the problem may hide for hours.

# inside the pod (if the JRE image has no tools: in a JDK container via kubectl debug)
top -H -b -n 1 -p 1 | head -20
#   PID USER  %CPU COMMAND
#    87 app   98.7 http-nio-8080-e
printf '%x\n' 87          # 57
jcmd 1 Thread.print > /tmp/td.txt
grep -A 15 'nid=0x57 ' /tmp/td.txt

On Linux every Java thread is a separate task, and top -H shows them separately. In the thread dump, the same ID sits in the nid field in hexadecimal.

Where to go depends on what you find:

  • in an http-nio-... or business thread: an infinite loop, a heavy regex (catastrophic backtracking), serialization of a huge JSON;
  • GC Thread#.. or G1 Conc#..: the problem is not in the code, the heap is full and the GC is running nonstop. Look at the GC log or jstat -gcutil 1 1000;
  • C2 CompilerThread: in the first few minutes after startup this is usually normal.

A single dump can mislead. Take 3-4 at 5-second intervals: if a thread sits in the same stack every time, that is the culprit.

For deeper analysis JFR is more convenient: jcmd 1 JFR.start duration=60s filename=/tmp/rec.jfr, then JDK Mission Control or an async-profiler flame graph shows directly which method is eating CPU. If there is no jcmd at all, kill -3 1 writes the thread dump to stdout.