Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Deadlock, Livelock & CPU 100%: Java Concurrency Troubleshooting with jstack & Arthas

This guide covers systematic concurrency troubleshooting: diagnosing deadlocks via Coffman conditions and ThreadMXBean patrols, resolving CPU 100% spikes with a five-step jstack/Arthas workflow, distinguishing livelock from starvation, detecting thread leaks via heap dumps, and implementing monitoring templates for production readiness.

Introduction

The article opens by framing concurrency bugs as issues that evade compile-time checks, unit tests, and even load tests — they only surface under specific timing conditions. The author argues that engineering maturity lies not in "knowing how to use" concurrency primitives but in having a repeatable, tool-driven troubleshooting playbook when things go wrong. Three real production incidents set the stage:

Incident 1: Scheduled Task vs. API Lock Order Reversal

A reconciliation job acquired lock A (account table) then lock B (ledger table), while a payment API acquired B then A. During a low-traffic window both ran simultaneously, creating a classic circular wait. Thread pools became entirely BLOCKED, the queue backed up to 80,000 tasks, and the deadlock persisted for 40 minutes until an on-call engineer ran jstack and saw Found one Java-level deadlock . Fix: enforce global lock ordering by resource ID (using a utility from Article 2) and add a 30-second ThreadMXBean.findDeadlockedThreads() patrol.

Incident 2: Shared HashMap Concurrent Writes Trigger Infinite Loop

A risk-control module used a static HashMap for rule storage. Concurrent put operations triggered resizing. In JDK 7 the head-insertion transfer algorithm caused the linked list to form a cycle, making get loop forever and driving CPU to 100%. Load balancer removed one instance, but the next instance quickly hit the same issue. JDK 8 switched to tail insertion (no cycle) but concurrent puts still lose data. Fix: replace with ConcurrentHashMap (Article 6) and audit all shared mutable state.

Incident 3: Thread Pool Queue Silently Fills, Graceful Shutdown Killed by kill -9

Deployment used a default 90-second force-kill timeout. The thread pool queue had already accumulated 50,000 tasks with no water-level monitoring. On shutdown the application continued draining the queue; after 90 seconds the process was forcibly terminated, losing all in-flight tasks. Recovery required an all-night reconciliation script run. Fix: monitor queue depth and BLOCKED thread count (Article 5), drain traffic before graceful shutdown.

Four Concurrency Pathologies: Classify Before Treating

The author defines four distinct failure modes with divergent symptoms and investigation paths:

Deadlock — Circular wait, low CPU, threads permanently BLOCKED, never self-heals.

Livelock — Threads actively retry/back off, high CPU, state changes but no progress.

Starvation — Scheduling bias, individual threads never acquire resources, CPU appears normal.

Leak — Threads or locks created but never released, thread count grows until unable to create new native thread.

All four manifest similarly (throughput drops, timeouts rise, thread count changes) but their CPU and thread-state signatures are completely different. Misclassification wastes hours. A three-second triage rule:

High CPU → check spin loops / infinite loops (Section 3 five-step).

Low CPU, threads stuck → check deadlock (Section 2 four conditions).

Thread count creeping up → check leak (named factory + two-dump comparison).

Normal CPU but long-tail latency → check starvation / critical-section degradation (Section 4).

Deadlock Pathology: Coffman Four Conditions & Breaking Strategies

Deadlock requires all four Coffman conditions simultaneously:

Mutual Exclusion — resource held by one thread at a time.

Hold and Wait — holding A while requesting B.

No Preemption — lock released only by holder.

Circular Wait — wait graph forms a cycle (A waits for B waits for A).

This is a diagnostic checklist, not theory: dump the threads, verify each condition; if all four hold, it's deadlock. Conversely, breaking any one condition prevents deadlock. Four engineering mappings:

Ordered Locking (breaks #4) — global ordering by resource ID, encapsulated in a utility (Article 2), zero cost, reviewable, templatable — first choice .

tryLock with Timeout (breaks #2/#3) — give up and back off if lock not acquired (Article 4), suitable for third-party callbacks where ordering can't be enforced.

Atomic Acquisition (breaks #2) — acquire all resources upfront, transactional style.

Open Calls (breaks #2) — never invoke external code (callbacks, RPC, event publishing) while holding a lock, avoiding uncontrolled lock acquisition paths.

Three Detection Axes (Same Core Algorithm)

jstack

prints Found one deadlock (JVM built-in detection). arthas thread -b identifies the blocker by counting waiters. ThreadMXBean.findDeadlockedThreads() runs a 30-second background patrol (source in Section 6.1).

Key nuance: many BLOCKED threads ≠ deadlock. Occasional BLOCKED is normal contention; sustained BLOCKED means slow critical section — check holder's hold time; rising BLOCKED trend signals spreading contention; only a confirmed deadlock is P1. Deadlock never self-heals — holders wait on each other with no thread able to break the cycle. The only "fix" is external intervention, hence detection must be continuous patrol, not post-incident dump. Incident 1's 40-minute backlog was the cost of missing patrol: detection + alert + stack trace = 3-minute diagnosis; without them, diagnosis takes hours.

Lock Ordering Convention Rollout

Inventory: list all code sites acquiring two or more locks simultaneously (search nested synchronized / lock).

Define order: sort by resource ID or fixed enum, encode in utility.

Enforce: add "multi-lock must use utility" to review checklist; PRs not using utility cannot merge.

Reading jstack 's deadlock section: it lists each thread's name, state, waited lock address, and held lock addresses. Pairing them reveals the full cycle. Copy this section directly into incident reports as ready-made four-condition evidence.

Toolchain: CPU 100% Five-Step Diagnosis to Line of Code

top -Hp <pid>

— find highest-CPU thread tid. printf '%x' <tid> — convert to hex (jstack nid is hex). jstack <pid> | grep <nid> — locate thread stack.

Read stack frames: find RUNNABLE frame stuck at a specific line.

Classify & fix: business infinite loop → code change; CAS spin → limit retries (Article 7); nid is GC thread → jstat -gcutil first, then heap tuning.

Five steps always reach the line; restarting on gut feel destroys the scene.

Four jstack Reading Essentials

Thread State — RUNNABLE means "runnable", not necessarily executing; waiting for IO ready also shows RUNNABLE.

Waiting For — BLOCKED threads show waiting to lock <address>.

Held By — that lock address appears in holder's stack as locked <address>; matching both gives the wait chain.

Deadlock Section — dump tail Found one deadlock directly lists cycle threads and locks.

Cross-validation is the soul of dump analysis: single dump is a snapshot; take two dumps 10 seconds apart. Unchanged state = true blockage (deadlock or slow critical section); changing state = contention jitter. On-call command cheat sheet: archive jstack, jstat -gcutil 1s sampling, arthas thread -b for blocker, thread -n 3 for busiest threads, jcmd Thread.print as jstack equivalent. Prefer Arthas in production: attach-on-demand, no restart, output redirected for forensics and postmortem.

When nid Is a GC Thread

GC thread saturating CPU isn't an infinite loop — it's memory pressure. First jstat -gcutil for GC frequency/overhead, then decide: leak hunt ( jmap -histo for bloated objects) or heap tuning (Article 5). Tweaking thread pools or code won't help; bottleneck is memory, CPU is just symptom.

Arthas Usage Caveats

Assess impact before attaching in production (agent injection); avoid during major change windows. thread -n 3 CPU stats are interval-sampled; short spikes may be missed — run repeatedly.

Enhanced commands ( watch / trace) have overhead; use for targeted diagnosis only, stop immediately.

Pathology Comparison & Top 6 Concurrency Pitfalls

Side-by-side comparison:

Deadlock — CPU low, constant BLOCKED, never self-heals.

Livelock — CPU high, state changes but no progress, rarely self-heals.

Starvation — CPU normal, individual threads never get resource, does not self-heal.

Leak — CPU normal then crash, thread count grows, does not self-heal.

Corresponding investigation entry points: deadlock → four conditions; livelock → retry logic; starvation → scheduling & critical section; leak → thread naming & ownership.

Top 6 Pitfalls (each maps to a prior article)

Missing unlock in finally (Article 2).

Double-checked locking without volatile (half-initialization, Article 3).

Shared HashMap concurrent writes (cycle/infinite loop, Article 6).

Chained get in async orchestration (degrades to serial, Article 8).

Unbounded spin (CPU saturation, Article 7).

Misusing notify (missed wakeup, Article 2).

These six cover ~80% of concurrency incidents. Code review against this table yields far higher hit rate than intuition. Common trait: unit tests green, load tests pass, production explodes.

Emergency SOP (Four Steps, Page 1 of On-Call Handbook)

Survive — rate limit, drain traffic, don't rush to restart.

Forensics — jstack twice (10s apart), jstat, top — all archived.

Classify — deadlock cycle? livelock spin? starvation? leak?

Remediate — fix, roll out, postmortem into handbook + team share.

Restarting before forensics = secondary incident: symptom gone, root cause buried forever. Forensics must precede restart.

Four Health Metrics (Zero-Intrusion via ThreadMXBean)

BLOCKED thread count — trend >10 → P2; sustained rise → P1.

Deadlock detected — patrol hit → immediate P1.

Total thread count — >50% above baseline → leak investigation.

Lock wait P99 — millisecond rise → critical section degradation.

All collected by a single scheduled task pushing to dashboard.

Thread Leak Investigation Path

Naming factory as safety net — every thread name = module-purpose-seq; unnamed threads are themselves anomaly signals.

Two-dump comparison — find thread groups with constant state and growing count over time.

Trace ownership — by thread name locate creation code, verify Executor.shutdown(), listener deregistration.

End stage: unable to create new native thread — any new thread creation fails, instance effectively dead — more catastrophic than deadlock.

Starvation Quantification for SLA

Gap between lock wait P99 and P999 is direct evidence of starvation — P999 far exceeding P99 means a few requests are starving. Fair lock is double-edged: eliminates queue-jumping starvation but throughput drops ~70% (Article 4 Incident 2). Production prefers shorten critical section + pool isolation — homogenize tasks per queue, starvation disappears naturally.

Production Templates: Patrol, Backoff, Forensics, Monitoring

5.1 Deadlock Patrol Template: 30s Interval, Alert with Stack (Incident 1 Fix)

Patrol is the highest-ROI investment. findDeadlockedThreads covers both synchronized and JUC locks (Section 6.1 source). On detection, getThreadInfo(ids, true, true) fetches lock + stack info; alert content enables zero-login, three-minute diagnosis.

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class DeadlockGuard {
    private static final ThreadMXBean TM =
        ManagementFactory.getPlatformMXBean(ThreadMXBean.class);

    /** 30s patrol: deadlock → P1 alert with stack */
    public void patrol() {
        long[] ids = TM.findDeadlockedThreads();
        if (ids == null) return; // no deadlock
        ThreadInfo[] infos = TM.getThreadInfo(ids, true, true);
        StringBuilder sb = new StringBuilder();
        for (ThreadInfo info : infos) {
            sb.append(info.toString());
            sb.append('
');
        }
        Alarm.p1("DEADLOCK", sb.toString());
    }
}

Operational details: patrol runs on dedicated single-thread scheduler (separate pool, rejection logs); alert deduplication — same cycle fires once, using "thread-set fingerprint" to avoid alert storms.

5.2 Livelock Defense Template: Limit + Exponential Backoff + Random Jitter

Livelock essence: "excessive politeness" — everyone yields, then retries simultaneously. Three-piece defense:

Limit — hard floor (exceed threshold → fallback, never spin forever).

Exponential backoff — wait grows with retry count.

Random jitter — prevents synchronized retry collisions after backoff.

public boolean commitWithBackoff(Rec rec) {
    int retry = 0;
    while (!tryCommit(rec)) {
        if (++retry > LIMIT) {
            metrics.inc("livelock.limit");
            return fallback(rec); // limit fallback
        }
        long backoff = (1L << retry) * 10;
        sleep(backoff + rand(0, backoff));
    }
    return true;
}

Retry count must be monitored: average retries >10 signals competition deterioration; limit/fallback is just a tourniquet — root cure requires eliminating contention source (sharding, staggering, shrinking critical section), a design-level fix.

5.3 Forensic Script: Run Before Restart (SOP Step 2)

Script value: pre-written, runnable by on-call in the 10-minute incident window — no time to assemble commands ad-hoc. Output archived to incident directory for postmortem and accountability.

#!/bin/bash
# Forensics at scene: run BEFORE restart
PID=$(jps -l | awk '/app.jar/{print $1}')
mkdir -p /tmp/fbi && cd /tmp/fbi
jstack $PID > stack-1.txt
sleep 10
jstack $PID > stack-2.txt
jstat -gcutil $PID 1000 10 > gc.log
top -b -n 1 -H -p $PID > top.txt
cp /proc/$PID/cmdline cmd.txt
# arthas: thread -b to find blocker
# deadlock confirm: check stack-*.txt tail sections

5.4 Health Metrics Collection: Four Metrics Zero-Intrusion

All four metrics from ThreadMXBean, one scheduled task collects all, pushes to dashboard, zero intrusion, zero config cost, directly reusable. deadlock field serves as P1 alert source; BLOCKED count and total threads trended.

public Map<String, Object> snapshot() {
    Map<String, Object> m = new HashMap<>();
    int blocked = 0;
    for (ThreadInfo ti : TM.dumpAllThreads(false, false)) {
        if (ti.getThreadState() == State.BLOCKED) blocked++;
    }
    m.put("blocked", blocked);
    m.put("threads", TM.getThreadCount());
    long[] dl = TM.findDeadlockedThreads();
    m.put("deadlock", dl != null ? 1 : 0);
    return m;
}

Eight-Point Checklist (Pre-Release + On-Call Patrol)

Lock ordering convention? tryLock with timeout?

Deadlock patrol integrated? Veto item: deadlock never self-heals; no patrol = guaranteed silent failure.

Thread naming factory?

BLOCKED monitoring?

Spin limited?

Dump forensics SOP?

Queue water-level alert?

Checklist survival depends on execution mechanism: embed in CI and PR templates as required checkboxes; patrol and monitoring as deployment checklist mandatory items. Unenforced checklists vanish with team turnover. Each item demands "check action" not just "check question": e.g., item 3 requires pasting patrol task's monitoring link.

Core Source Code: Detection & Cycle Formation Logic

6.1 findDeadlockedThreads : Unified Graph for Two Monitor Types

Detection core: "build graph, find cycle". Snapshot each thread's held locks and waited locks; if thread A waits for a lock held by thread B, draw edge A→B. Threads on cycle are deadlocked. JDK implementation in two phases: first check synchronized monitor deadlocks, then extend to ownable synchronizer ( ReentrantLock, Semaphore, etc.).

// ThreadMXBean detection skeleton (simplified)
public long[] findDeadlockedThreads() {
    // Phase 1: monitor deadlocks (synchronized)
    long[] ids = findMonitorDeadlockedThreads();
    // Phase 2: extend to ownable synchronizer
    // Snapshot each thread:
    // lockedOwnables = held synchronizers
    // waited synchronizer's owner thread
    // Build graph: ThreadA -(waits)-> Synchronizer -(heldBy)-> B
    // DFS coloring: white=unvisited, gray=onStack, black=done
    // Back to gray node = cycle found
    // Return deduped thread IDs in cycle, null if none
}

This is why the patrol template works out-of-the-box: it covers JUC locks, not just synchronized. Caveat: it only confirms deadlock after it has occurred; cannot predict. Prevention still needs ordered locking (pre) + timeout (fallback) as dual defense; patrol automates the "confirmation" step.

6.2 JDK 7 HashMap.transfer : Head Insertion Creates Cycle (Incident 2 Root Cause)

Incident 2's root cause in JDK 7 resize code: head insertion under concurrency makes linked list cyclic . T1 records e1 and e1.next then suspends; T2 moves entire chain (order reversed); T1 resumes and continues head-inserting using stale references — e1 and e2 point to each other, cycle formed, subsequent get never terminates, CPU 100%.

// JDK7 HashMap.transfer (resize, head insert)
void transfer(Entry[] newTable) {
    Entry[] src = table;
    for (int j = 0; j < src.length; j++) {
        Entry e = src[j];
        if (e != null) {
            src[j] = null;
            do {
                Entry next = e.next;
                // Head insert: new bucket head becomes e.next
                e.next = newTable[j];
                newTable[j] = e;
                e = next;
            } while (e != null);
        }
    }
}
// Concurrent timing: T1 records e1/e2 then suspends, T2 completes
// move (list reversed), T1 resumes head-inserting with old refs,
// e1 and e2 point to each other forming cycle, get loops forever

JDK 8 switched to tail insertion (no cycle), but concurrent puts still lose data — "upgrade JDK and you're safe" is an illusion. Shared containers must use ConcurrentHashMap (Article 6). This code pins a concrete CPU 100% cause to line level: step 4 of five-step diagnosis reads stack, sees HashMap.transfer — that's it.

6.3 arthas thread -b : Waiter Count Finds Blocker

Principle: count waiters per blocker; holder with most waiters = blocker source — one thread stuck in slow critical section, dozens queued, count reveals it instantly.

// arthas thread -b core (simplified):
// Find holder blocking most other threads
public Map<Long, Long> countBlockers() {
    Map<Long, Long> holders = new HashMap<>();
    for (ThreadInfo ti : dumpAllThreads(false, false)) {
        if (ti.getThreadState() == State.BLOCKED) {
            long owner = ti.getLockOwnerId();
            holders.merge(owner, 1L, Long::sum);
        }
    }
    // Holder with max waiters = blocker source
    return holders;
}

6.4 Wait Chain Reconstruction: Manual Cycle Detection from Dump

Understanding the detection algorithm lets you manually trace: from any BLOCKED thread, follow "waited lock → holder" repeatedly; revisiting a thread = cycle = deadlock . jstack 's Found one section is the polished output of this chain.

// Generic algorithm to reconstruct wait chain from dump:
public void printChain(long startId, Map<Long, ThreadInfo> map) {
    long cur = startId;
    Set<Long> seen = new HashSet<>();
    while (true) {
        ThreadInfo now = map.get(cur);
        if (now == null) break;
        System.out.printf("%s waits %s%n", now.getThreadName(), now.getLockName());
        if (!seen.add(cur)) { System.out.println("DEADLOCK"); break; }
        cur = now.getLockOwnerId();
        if (cur == -1) break; // chain end, no deadlock
    }
}

Detection boundary: findDeadlockedThreads only finds lock deadlocks, not resource suspension — threads stuck in socket read, JDBC wait, etc., never enter lock wait graph; they show as WAITING/RUNNABLE long-stalled — many "false deadlocks" are actually this. Diagnosis relies on timeouts (connect/read timeout mandatory) and dump comparison, not deadlock detection.

Seven Cost-Benefit Accounts

Detection Account — 30s patrol CPU ~zero ( dumpAllThreads ms-level); benefit: deadlock from "40-min queue backlog then discovered" to "30s alert with stack". Incident 1's 40 minutes = cost of no patrol. Highest ROI in series.

Convention Account — lock ordering utility once, team-wide reuse, reviewable; cheaper by orders of magnitude than post-incident retrospectives. Convention blocks occurrence; patrol catches leakage — both essential.

Emergency Account — forensic script pre-written in handbook, 10-min scene capture; saves restart-lost-root-cause secondary incidents and reproduction costs. Restart destroying scene = costliest concurrency debugging error.

Monitoring Account — four health metrics one-time setup; shifts from "user reports then we know" to "metrics know first". User-reported concurrency incidents take an order of magnitude longer to locate, often already at financial loss stage.

Leak Account — naming factory 10-min investment; leak diagnosis (two-dump diff) takes hours. Once unable to create new native thread hits, instance is scrap. Naming isn't code hygiene; it's observability foundation.

Spin Account — limit + backoff few lines; saves CPU 100% instance eviction cascade (Article 7 Incident 1 sequel). Retry count monitored, turns "competition worsening" from feeling into curve.

Ecosystem Account — this article closes the loop on first three: Article 2 lock ordering, Article 5 pool water-level, Article 6 container selection, Article 7 spin limits, Article 8 orchestration fallback — all converge into one on-call handbook and eight-point checklist. Concurrency knowledge only counts when it becomes executable check actions.

20 Interview Questions (with Answers)

The article concludes with 20 Q&A covering deadlock conditions, ordered locking, tryLock, deadlock vs BLOCKED, CPU 100% steps, RUNNABLE semantics, livelock vs deadlock, starvation causes/avoidance, thread leak causes/diagnosis, two-dump rationale, arthas thread -b principle, HashMap infinite loop, notify misuse, spin CPU 100%, graceful shutdown kill -9, findDeadlockedThreads vs findMonitorDeadlockedThreads, alert with stack, SOP four steps, health metrics, prevention checklist. Each answer mirrors the article's practical, tool-first, process-oriented style.

One-Page Cheat Sheet

Four boxed summaries:

Deadlock & Breaking: Four conditions (mutex/hold-wait/no-preemption/circular-wait) all required; break any one. Ordered locking first (Article 2 util), tryLock timeout fallback, atomic acquisition & open calls as backup. jstack Found one + MXBean patrol dual confirm. Patrol 30s, alert with stack.

Toolchain: CPU 100% five steps: top -Hp → hex → jstack grep nid → read stack → classify fix. Dump four keys: RUNNABLE semantics / waiting-to-lock / locked holder / Found one cycle. Two dumps 10s apart = prerequisite for conclusion. Production prefers Arthas ( thread -b for blocker).

Pathology & Pitfalls: Deadlock low CPU constant BLOCKED no self-heal / Livelock high CPU spin no progress / Starvation normal CPU individual threads starve / Leak thread count creeps — three-second triage then treat. Top 6: missing unlock, DCL no volatile, HashMap shared write, chained get, unbounded spin, notify misuse — review by table.

On-Call Scope: SOP: survive → forensics → classify → remediate; forensics script pre-written, forensics BEFORE restart. Health four metrics (BLOCKED/deadlock/thread-count/lock-wait-P99) on dashboard. Eight-point checklist pre-release, item 3 (deadlock patrol) veto.

One-liner for on-call channel: High CPU → five steps; threads stuck → two dumps; deadlock found → P1; thread count creeping → leak; forensics ALWAYS before restart. Post this, even newcomers launch correct flow in three minutes — troubleshooting system's value ultimately shows on the least experienced person.

Article walks full chain from three incidents: "pathology → breaking → toolchain → pathology map → practice". Coffman turns deadlock from mysticism into ruler; five steps turn CPU 100% from feeling into commands; four-type classification turns on-call from guessing into investigating; patrol/backoff/forensics/monitoring turn troubleshooting into infrastructure. Essence of concurrency troubleshooting: "make the accidental inevitably visible" — deadlock doesn't self-heal, so detection must be continuous; timing irreproducible, so forensics must precede restart. Eight-point checklist and Top 6 pitfalls are the takeaways.

Next article "Production Finale": consolidates all ten articles' templates and checklists — thread pool three config tables, lock three-question checklist, JMM health, AQS selection four questions, tuning five-step loop, container selection, CAS safety net, CF orchestration templates, this article's on-call handbook, plus one complete "incident retrospective panorama case".

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

deadlockConcurrentHashMapproduction debuggingArthasthread leakjstackThreadMXBeanlivelockCoffman conditionsconcurrency troubleshootingCPU 100%starvation

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion