Hard java java-21

How do you troubleshoot high CPU in a Java service?

The 30 second answer

First I confirm it's the Java process and check whether garbage collection is burning the CPU, using the GC logs. If not, I find the hot threads: take a few thread dumps a few seconds apart and see which stacks stay busy. Then I record a short Flight Recorder profile to find the hot methods. Typical causes are busy loops, retry storms, heavy regex or serialization, and excessive logging.

  1. Confirm the source. Is the JVM using the CPU, and is it GC? Check GC logs (-Xlog:gc*) or jstat -gcutil <pid> 1s. Constant GC usually means memory pressure, so switch to the GC-pause playbook below.
  2. Find hot threads. On Linux, top -H -p <pid> shows per-thread CPU. Convert the busy thread ID to hex and find it as nid=0x... in a thread dump from jcmd <pid> Thread.print. Take 3 to 5 dumps a few seconds apart; stacks that stay RUNNABLE in the same code are the suspects.
  3. Profile. Record with JDK Flight Recorder, which has low overhead and is designed for production use:
   jcmd <pid> JFR.start duration=60s filename=cpu.jfr

Open the file in JDK Mission Control and look at hot methods and threads.

  1. Fix and verify. Common causes: tight loops, retry storms without backoff, catastrophic regex backtracking, serializing huge objects, logging in hot paths, lock spinning. Measure again after the fix.

Sources: jcmd, Troubleshooting Guide: Diagnostic Tools (JFR), java command: -Xlog, jstat

Sources (0)
See inline citations in the answer above.