advancedModern Java & Architecture

How would you debug a high-CPU issue caused by a thread spinning?

The first step is to identify which specific thread is consuming the CPU, which on Linux you can do with top -H -p <PID> to see per-thread CPU usage and note the thread ID (TID) of the hot thread. Next, convert that TID to hexadecimal, for example with printf "%x\n" TID, because Java thread dumps identify threads by their hexadecimal native ID. Then run jstack <PID> to capture a full thread dump, and locate the thread whose nid field matches the hex TID you computed -- its stack trace shows exactly what code that thread is currently executing. Common culprits behind a spinning thread include a hand-written busy-wait loop such as while (!ready) {}, a compare-and-swap loop retrying excessively under very high contention, an outright infinite-loop bug such as the classic Java 7 HashMap resize corruption under concurrent access, or lock contention inside String.intern(). The fix depends on the cause: replace a busy-wait with proper wait/notify or LockSupport.park(), switch a high-contention counter to LongAdder, or replace an unsafe HashMap with ConcurrentHashMap.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What is the difference between optimistic and pessimistic locking, and where does each apply?← Back to all Java Concurrency & Multithreading questions