Java Concurrency in Production: Post-Mortem, Decision Trees & Automated Checklists
This final episode of a 10-part Java concurrency series uses a flash sale post-mortem with three simultaneous failures to demonstrate how to convert scattered knowledge into team-wide capability through decision trees, automated checklists, and runtime guardrails.
Reading font

1. Panoramic Post-Mortem: Three Strikes in One Flash Sale
The order system comprised Order Service, Inventory Service, and Compensation Task, all deployed two weeks before the sale with passing load tests and green unit tests. Three latent defects surfaced under real traffic:
Strike 1 – Orchestration degraded to serial (20:00): Order page aggregated details, price, and inventory via three RPCs. The developer used supplyAsync but called get() in the chain, turning parallel calls into sequential relay. P99 rose from 80 ms to 480 ms (Episode 8 accident replay); 5× traffic pushed thread-pool queueing, P99 > 2 s. Diagnosed in 10 min via arthas trace showing RPC times added not overlapped. Fixed by switching to thenCompose chain + dedicated business pool (Episode 8 template).
Strike 2 – Oversell of 37 items (22:20): Inventory deduction used check-then-act: read balance, judge sufficiency, write back. Between judge and write another thread deducted the same stock, losing updates. Fixed with atomic API + row lock (Episode 7 template).
Strike 3 – Compensation task deadlock (23:40): Compensation held flow-table lock then requested account-table lock; payment API held account lock then requested flow lock — classic lock-order inversion (Episode 2 accident replay). Fixed with lockSorted utility (Episode 2).
All four fixes came from earlier episodes' copy-paste templates. Timeline: 20:40 P99 alert → 21:10 confirmed serial orchestration → 21:50 scaled down to 300 ms → 22:20 reconciliation found oversell → 23:00 compensation BLOCKED pile-up → 23:40 MXBean deadlock check fired P1 with stack evidence. Each fix left forensic traces: two jstack dumps, arthas trace screenshots, reconciliation SQL, deadlock stacks. Retrospective produced four process improvements now embedded in workflow:
CompletableFuture must bring its own business pool (PR veto item).
Deduction operations must use atomic API; get+set banned (coding standard).
Multi-lock must use ordering utility (scaffold built-in).
Deadlock patrol on on-call dashboard, 30 s detection = P1.
Why did three defects hide until peak? Load tests used fixed short mock latencies (averaging away tail latency), dispersed inventory keys (near-zero same-row contention), and lacked the pre-dawn scheduled-task window where both paths run simultaneously. Load tests verify capacity, not correctness; correctness needs reviews, health checks, and drills.
2. Defense System: Four Lines & Two Tool Maps
Reorganizing the nine episodes by "when to use" yields two maps:
Coding-time tools (9): synchronized default (Ep2), ReentrantLock four needs (Ep4), volatile switch/publish (Ep3), Atomic/LongAdder counting (Ep7), ConcurrentHashMap shared container (Ep6), CopyOnWriteArrayList read-heavy (Ep6), BlockingQueue producer-consumer (Ep6), CompletableFuture IO orchestration (Ep8), explicit pool build (Ep1/5).
Runtime tools (9): dual jstack diff, jstat GC sampling, top -Hp thread pin, arthas thread -b/-n, ThreadMXBean deadlock patrol, pool five-metric dashboard, lock-wait P99, dump forensics SOP, retrospective four-questions.
These form four defense lines: correct selection (decision tree), correct implementation (templates), adequate monitoring (metrics), efficient troubleshooting (SOP). Most teams miss the last two — yet they save the night. Build order: monitoring first (fast, zero intrusion — pool metrics + deadlock patrol in one week), then SOP/drills, then harden selection/implementation. Invisible problems cannot be fixed — make concurrency state visible first.
3. Selection Decision Tree: One Page, Eight Questions
Anxiety comes from tool-first thinking. This tree starts from requirements, asks eight questions sequentially, stops on first hit, minimal-tool principle:
Just a switch or publish flag? → volatile (Ep3 four-questions).
Counting accumulation? → Single-point accuracy: Atomic; high-contention write-only: LongAdder (Ep7).
Shared key-value container? → ConcurrentHashMap + computeIfAbsent (Ep6).
Read-heavy, write-rare, small list? → CopyOnWriteArrayList (Ep6 criteria).
Producer-consumer decoupling? → BlockingQueue (Ep6 five implementations).
Multi-step IO orchestration? → CompletableFuture + dedicated pool (Ep8).
Need timeout/fairness/multiple conditions? → ReentrantLock + Condition (Ep4).
None of the above? → synchronized default — don't over-engineer.
Two real misuse cases: (1) Adding ReentrantLock to a config read (few thousand QPS) — tree hits Q3, correct answer is ConcurrentHashMap volatile read, no lock needed. (2) Wrapping a one-shot remote notify in CompletableFuture — tree hits Q8, simple threadPool.submit suffices; CF adds callback stack and timeout complexity. The tree blocks not just bugs but the "learned-it-must-use-it" over-engineering impulse.
4. Production Practice: Three Final Checklists
Checklist 1: Code Review Ten Items (PR template checkboxes)
Shared mutable state has synchronization?
Lock object is stable business object?
Multi-lock paths use ordering utility?
CF brings dedicated pool, not commonPool?
Counting uses atomic API, bans get+set?
Threads have naming factory and upper bound?
Spin has bounded retries and backoff?
Wait uses while re-check? unlock in finally?
Containers ban shared HashMap?
Checklist 2: Pre-Release Eight Health Checks (shared dashboard with on-call)
Deadlock patrol on dashboard (veto: no patrol = no release). BLOCKED count trend monitoring.
Pool five metrics collected.
Queue watermark & rejection alerts.
Thread count baseline & leak alerts.
Lock-wait P99 on dashboard.
Dump forensics SOP rehearsed.
Timeouts & backoffs configured end-to-end.
Checklist 3: On-Call Three-Piece Set
Decision tree (CPU high → five steps; thread stuck → dual dump; deadlock found → P1).
Command card ( jstack x2, jstat, top -Hp, thread -b, patrol dashboard link).
Doctrine (forensics before restart, fix then ramp, retrospective four-questions, improvements into process with verification).
Checklists not in process expire in three months. Four code deliverables automate the lists:
ConcurrencyBootstrap (SmartLifecycle): Auto-wires deadlock patrol (30 s, Ep2/9), pool metrics (10 s, Ep5), graceful shutdown (drain traffic, wait 30 s). Default values = strongest standard.
ArchUnit rules: Bans Executors factory, raw Thread construction, shared HashMap fields — turns review rules into unit tests.
Drill script: Spring Boot app that deliberately creates lock-order deadlock (Ep2) and CPU-spinning CAS (Ep7); validates patrol detects in 30 s, on-call locates via handbook in <10 min.
RetroGate: Maps incident ID → improvement gates (CF pool, atomic stock, lock order, deadlock guard); release pipeline blocks until Gate::verified passes.
Rollout order: Bootstrap (highest ROI, smallest change) → ArchUnit (blocks new issues) → Quarterly drills → RetroGate (mature process). Small teams start with three checklists + bootstrap, two-week cycles.
5. Core Source Review: Four Skeletons Spanning Ten Episodes
No new source; instead strings together four backbone snippets from earlier episodes — from "one instruction" to "one ecosystem".
Atomic layer — lock cmpxchg (Ep7): Hardware bedrock of all atomicity. Failure returns current value, fueling CAS spin loops. x86 lock cmpxchg [mem], reg = cache-line lock + full barrier (same root as volatile write StoreLoad, Ep3 §4). Java side: Unsafe.compareAndSwapInt → native → cmpxchg; AQS state, Atomic, LongAdder base all stand on this instruction.
Synchronizer layer — AQS acquire (Ep4): volatile int state + CAS + CLH queue. tryAcquire is plugin (fair vs non-fair = one hasQueuedPredecessors check). acquireQueued: park only when predecessor SIGNAL; wake → retry from step 1 — spin/park boundary = observed contention level.
Scheduling layer — ThreadPoolExecutor.execute triple re-check (Ep1/5): ctl packs state (high 3 bits) + count (low 29 bits). Three re-reads of ctl because each bit-field may change after read: core check → queue offer → shutdown check → zero-worker guard → max check → reject.
Dispersion layer — LongAdder.add (Ep7): Four-level funnel: CAS base → create cells → probe locate → expand. Same idea as Ep6
ConcurrentHashMapCounterCell— "divide and conquer" hotspot.
One-sentence chain: cmpxchg owns single atomicity, AQS assembles it into locks/synchronizers, thread pool uses it to schedule cooperation, LongAdder disperses contention at the hot spot. Read source by "layer" not "line" — each layer answers one question: atomic layer "how to avoid conflict", synchronizer "what when conflict", scheduler "who does the work", dispersion "what when everyone crowds one point". Ten episodes' source snippets total <300 lines but are the load-bearing walls of JUC.
6. Seven Accounts: Final Tally
Capability account: Net value not stock. Three transferable meta-skills: decide by tree, implement by template, troubleshoot by SOP — portable across languages/frameworks. Ten skills = complete concurrency engineer stack.
Cost account: 10-15 h direct learning + template refactoring hours. vs. no-system: deadlock locate = hours, oversell reconcile = days. ROI breaks even on first intercepted incident.
Checklist account: 21 items total. Maintenance = quarterly half-day drill + one-time PR/CI config. Payoff: defects intercepted at review, release, on-call. Checklists are the ten-episode compression pack — non-readers reach 70/100 via checklists alone.
Tool account: 18 entries, all JDK built-in or open-source (Arthas, ArchUnit). Barrier is not tool rarity but usage discipline.
Retrospective account: Four improvements automated (bootstrap, ArchUnit, drill, gate). Next same-class incident locate time → minutes. Formula: automation degree × enforcement strength ; memo-only improvements = zero value.
Inheritance account: 33 real scenarios (3 per episode + 3 finale). New-hire curriculum: two weeks read ten episodes, one month drill, three months solo on-call. Inheritance cost collapses via checklists.
Ecosystem account: Every piece — AQS, CHM, LongAdder, CF — sits on same volatile + CAS foundation (Ep3), which underpins Spring, Netty, Kafka clients. Master ten episodes, read any framework concurrency source with intuition.
7. Twenty Interview Questions (with Answers)
Covers thread pool parameter order, Executors ban rationale, lock object three principles, happens-before top three rules, volatile vs lock boundaries, AQS core trio, fair vs non-fair trade-off, Condition advantages, dynamic pool resize semantics, queue length dual-budget, CallerRunsPolicy production suitability, CHM three-tier locking, CopyOnWriteArrayList criteria, AtomicLong vs LongAdder selection, ABA when to guard, CompletableFuture.get() hazard, commonPool three pits, deadlock confirm/prevent, CPU 100% five-step SOP, team asset immersion.
8. One-Page Cheat Sheet
Condenses post-mortem, tool maps, decision tree, three checklists, on-call doctrine: Concurrency capability = minimal tool + checklist process + rehearsed troubleshooting — three things done right long-term.
9. Series Conclusion
Structure: Ep1-2 foundations (thread/pool/lock usage), Ep3-4 principles (JMM & AQS twin pillars), Ep5-8 practice (tuning, containers, CAS, orchestration), Ep9-10 closure (troubleshooting system & team assets). Three accidents open each episode, seven main threads run throughout, four production code segments per episode, seven accounts + twenty questions per episode — this structure itself is a "from novice to on-call" concurrency syllabus. Final advice: print Figure 3 (tool maps) and Figure 4 (decision tree) on your desk — code by tree, debug by map; two diagrams cover all daily actions. Ten episodes end at two diagrams; two diagrams end in muscle memory. Concurrency has no mysticism, only rules, templates, and checklists. Series complete; your practice starts now — from today's first PR template, from the next dump forensics.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.