Production Diagnosis: Thread Dumps, Heap Dumps, JFR & async-profiler
It's 2 AM. The API's p99 went from 150ms to 3 seconds, CPU is pinned at 95%, and it works fine on your laptop. Restarting "fixed" it last time — for four hours. This post is the toolkit for the time restarting doesn't fix it: four tools, each answering one question, mapped to the symptom in front of you.
The whole post in one diagram. Pick the symptom, grab the tool:
Every example below was run, not imagined: JDK 21.0.3, one lab app containing four production sins, and the real output of jstack, jmap, ThreadMXBean, -Xlog:gc, and the in-process JFR API. Where a tool wasn't available in this lab (async-profiler), I say so plainly instead of inventing output.
1. The lab specimen: one app, four sins
Diagnosis is a reading skill, and reading needs a specimen. This one program commits all four sins at once — a CPU burner, a memory leak, a lock-ordering deadlock, and a saturated thread pool:
import java.util.*;
import java.util.concurrent.*;
public class ProdMystery {
static final List<byte[]> LEAK = new ArrayList<>();
static final Object lockA = new Object(), lockB = new Object();
public static void main(String[] args) throws Exception {
// Sin 1: a thread burning CPU in a hot loop
Thread spinner = new Thread(() -> {
long x = 0;
while (true) { x += Math.sqrt(x + 1); } // never-ending busy work
}, "cpu-spinner");
spinner.setDaemon(true);
spinner.start();
// Sin 2: slow memory leak, ~1MB every 200ms held by a static list
Thread leaker = new Thread(() -> {
try {
while (true) { LEAK.add(new byte[1024 * 1024]); Thread.sleep(200); }
} catch (InterruptedException ignored) { }
}, "memory-leaker");
leaker.setDaemon(true);
leaker.start();
// Sin 3: classic lock-ordering deadlock
Thread t1 = new Thread(() -> {
synchronized (lockA) { sleep(100); synchronized (lockB) { } }
}, "deadlock-1");
Thread t2 = new Thread(() -> {
synchronized (lockB) { sleep(100); synchronized (lockA) { } }
}, "deadlock-2");
t1.setDaemon(true); t2.setDaemon(true);
t1.start(); t2.start();
// Sin 4: a saturated pool — 2 workers, 50 tasks, each sleeping 3s
ThreadFactory daemonFactory = r -> {
Thread t = new Thread(r, "pool-worker");
t.setDaemon(true);
return t;
};
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), daemonFactory);
for (int i = 0; i < 50; i++) {
pool.submit(() -> sleep(3000));
}
// A reporter so you can watch the queue pile up
Thread reporter = new Thread(() -> {
for (int i = 0; i < 9; i++) {
System.out.printf("[pool] active=%d queued=%d completed=%d%n",
pool.getActiveCount(), pool.getQueue().size(), pool.getCompletedTaskCount());
sleep(10_000);
}
}, "pool-reporter");
reporter.setDaemon(true);
reporter.start();
Thread.sleep(120_000); // give yourself time to diagnose
}
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException ignored) { }
}
}
Compile it, run it in one terminal, find its PID with jps -l in another. Everything from here on is real output from that running app:
$ javac ProdMystery.java && java ProdMystery > prodmystery.log 2>&1 &
$ jps -l
22340 ProdMystery
$ head -2 prodmystery.log
[pool] active=2 queued=48 completed=0
[pool] active=2 queued=42 completed=6
Read that second line like an on-call engineer: 2 threads active, 48 tasks waiting in the queue, 0 completed after ten seconds. That is what a saturated pool looks like from the inside — work arriving faster than workers can drain it. In production you'd get these numbers from a metrics endpoint or a JMX bean; here the reporter prints them so you can watch the pile-up in real time.
2. Thread dumps: where is every thread right now?
A thread dump is a snapshot of every thread's stack trace at one instant. It answers "are my threads stuck, and where?" — nothing more, nothing less. Two ways to take one against a running JVM:
jstack <pid> > dump1.txt # the classic
jcmd <pid> Thread.print > dump1.txt # the modern equivalent
Both were available on this machine (JDK 21 ships both). Now read the dump. First, the CPU burner:
$ grep -A 6 '"cpu-spinner"' dump1.txt
"cpu-spinner" #18 [22359] daemon prio=5 os_prio=0 cpu=3614.07ms elapsed=16.58s tid=0x... nid=22359 runnable [0x...]
java.lang.Thread.State: RUNNABLE
at ProdMystery.lambda$main$0(ProdMystery.java:16)
at ProdMystery$$Lambda/0x00007ed85c000a00.run(Unknown Source)
at java.lang.Thread.runWith(java.base@21.0.3/Thread.java:1596)
at java.lang.Thread.run(java.base@21.0.3/Thread.java:1583)
Two details worth a senior's eye. First, the top frame is the lambda itself, not Math.sqrt — the JIT inlined the call, so the "hot method" shows up as your own line 16. Profilers and dumps show you compiled code, not source code; inlining moves frames around. Second, cpu=3614.07ms against elapsed=16.58s of wall time is low for a busy loop — on this shared lab box the thread wasn't scheduled the whole time. CPU time vs elapsed time is the first thing to compare when a "hot" thread looks lukewarm.
One dump is a snapshot; three dumps five seconds apart showing the same stack is proof of a hot spot:
$ for i in 1 2 3; do jstack 22340 > dump$i.txt; sleep 5; done
$ for f in dump1.txt dump2.txt dump3.txt; do echo "== $f"; grep -A 1 '"cpu-spinner"' $f | grep "at ProdMystery"; done
== dump1.txt
at ProdMystery.lambda$main$0(ProdMystery.java:16)
== dump2.txt
at ProdMystery.lambda$main$0(ProdMystery.java:16)
== dump3.txt
at ProdMystery.lambda$main$0(ProdMystery.java:16)Same thread, same line, ten seconds apart. That's not a coincidence — that's your culprit. This is the single most useful thread-dump habit: never trust one dump for CPU diagnosis; trust three.
Now the deadlock participants:
$ grep -A 9 '"deadlock-1"' dump1.txt | head -11
"deadlock-1" #20 [22361] daemon prio=5 os_prio=0 cpu=0.72ms elapsed=16.57s tid=0x... nid=22361 waiting for monitor entry [0x...]
java.lang.Thread.State: BLOCKED (on object monitor)
at ProdMystery.lambda$main$2(ProdMystery.java:32)
- waiting to lock <0x000000008b9007c8> (a java.lang.Object)
- locked <0x000000008b9007d8> (a java.lang.Object)
...
Read it like a sentence: deadlock-1 is BLOCKED at line 32, waiting to lock one monitor while holding another. Its partner shows the mirror image — waiting on ...7d8 while holding ...7c8. Each thread holds exactly the lock the other wants. And you don't even have to do that cross-referencing yourself, because the dump ends with this:
Found one Java-level deadlock:
=============================
"deadlock-1":
waiting to lock monitor 0x00007ed8440015b0 (object 0x000000008b9007c8, a java.lang.Object),
which is held by "deadlock-2"
"deadlock-2":
waiting to lock monitor 0x00007ed8400015b0 (object 0x000000008b9007d8, a java.lang.Object),
which is held by "deadlock-1"
Java stack information for the threads listed above:
===================================================
"deadlock-1":
at ProdMystery.lambda$main$2(ProdMystery.java:32)
- waiting to lock <0x000000008b9007c8> (a java.lang.Object)
- locked <0x000000008b9007d8> (a java.lang.Object)
...
"deadlock-2":
at ProdMystery.lambda$main$3(ProdMystery.java:35)
- waiting to lock <0x000000008b9007d8> (a java.lang.Object)
- locked <0x000000008b9007c8> (a java.lang.Object)
...
Found 1 deadlock.
The JVM does your first analysis for you. When a production dump contains a Found one Java-level deadlock section, read it first — it's the cheapest win in the whole toolkit. (No deadlock? The section simply isn't there. Absence of the section is itself an answer: your hang is something else.)
Finally, the pool workers — the "piling up" half of sin 4:
$ grep -A 8 '"pool-worker"' dump1.txt | head -10
"pool-worker" #22 [22363] daemon prio=5 os_prio=0 cpu=1.13ms elapsed=16.51s tid=0x... nid=22363 waiting on condition [0x...]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep0(java.base@21.0.3/Native Method)
at java.lang.Thread.sleep(java.base@21.0.3/Thread.java:509)
at ProdMystery.sleep(ProdMystery.java:67)
at ProdMystery.lambda$main$5(ProdMystery.java:49)
...
Both workers parked in sleep — busy, not stuck. The dump tells you the workers are fine; the queue is the problem, and queues don't appear in thread dumps. That's why the reporter line (queued=48) matters: thread dumps show threads, never queues. Pool saturation is diagnosed by pairing a dump (workers healthy, doing expected work) with queue depth from metrics.
3. Reading thread states: RUNNABLE, BLOCKED, WAITING
Three states carry ~95% of the diagnostic signal. Learn to read them as verdicts, not vocabulary:
A few reading rules that turn the diagram into reflexes:
- RUNNABLE + high CPU + unmoving stack = hot code. That's the whole CPU-diagnosis game at the dump level. (Caveat from the lab: JIT inlining can hide the "real" hot method inside your own frame — line 16 was really
Math.sqrt.) - Many threads BLOCKED on the same monitor = contention. One BLOCKED pair in a cycle = deadlock. The dump's lock addresses (
waiting to lock <...7c8>vslocked <...7d8>) are how you match holders to waiters by hand. - WAITING threads are usually innocent. A web server at rest shows hundreds of parked threads. Don't chase them — chase the ones that should be progressing but aren't.
- Dumps can't see queues, latches, or external systems. The pool dump above proves the workers are healthy; it says nothing about the 48 queued tasks. Pair dumps with metrics (queue depth, pool size) for the full picture.
4. Deadlock detection you can run yourself
The Found one Java-level deadlock section comes from ThreadMXBean.findDeadlockedThreads() — the same API your code can call. This matters because you can wire it into health checks and alerting instead of waiting for a human to take a dump. Proof it works, on a live deadlock, in-process:
import java.lang.management.*;
public class SelfDeadlockCheck {
static final Object A = new Object(), B = new Object();
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(() -> {
synchronized (A) { nap(200); synchronized (B) { } }
}, "order-A-first");
Thread t2 = new Thread(() -> {
synchronized (B) { nap(200); synchronized (A) { } }
}, "order-B-first");
t1.setDaemon(true); t2.setDaemon(true);
t1.start(); t2.start();
Thread.sleep(1000); // let the deadlock form
ThreadMXBean mx = ManagementFactory.getThreadMXBean();
long[] dead = mx.findDeadlockedThreads();
System.out.println("findDeadlockedThreads() -> "
+ (dead == null ? "null (no deadlock found)" : dead.length + " deadlocked threads"));
if (dead != null) {
for (ThreadInfo ti : mx.getThreadInfo(dead, true, true)) {
System.out.println(ti.getThreadName()
+ " state=" + ti.getThreadState()
+ " waiting on " + ti.getLockName()
+ " held by " + ti.getLockOwnerName());
}
}
}
static void nap(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}$ javac SelfDeadlockCheck.java && java SelfDeadlockCheck
findDeadlockedThreads() -> 2 deadlocked threads
order-A-first state=BLOCKED waiting on java.lang.Object@279f2327 held by order-B-first
order-B-first state=BLOCKED waiting on java.lang.Object@28a418fc held by order-A-first
Two things to notice. First, it returns null when there's no deadlock — so a health check is literally if (mx.findDeadlockedThreads() != null) page_someone(). Second, it reports who holds the lock each thread is waiting on — the cycle is visible in two lines, no dump archaeology required. This is the same detector jstack runs; you're just calling it directly. (It finds deadlocks on synchronized monitors and on java.util.concurrent ownable synchronizers like ReentrantLock — use findMonitorDeadlockedThreads() if you only care about the synchronized kind.)
5. async-profiler: who is eating the CPU?
Thread dumps show you stuck threads. For busy threads — the 95%-CPU scenario — you want a profiler that samples the whole JVM with negligible overhead and draws a flame graph: a picture where the width of each box is the share of CPU time spent in that method. The standard tool is async-profiler.
Honesty note, stated plainly: async-profiler was not installed on this lab machine, so there is no real flame-graph output below — and I'm not going to invent one. What follows is what the commands look like and how to read their results, so you can run them yourself. Everything else in this post is real output; this section is clearly marked as "bring your own run".
# What the command looks like (NOT run here — no fake output invented):
./profiler.sh -d 30 -f cpu.html <pid> # 30s CPU profile -> interactive flame graph
./profiler.sh -d 30 -e alloc -f alloc.html <pid> # allocation profile: who creates garbage
./profiler.sh -d 30 -e lock -f lock.html <pid> # lock profile: where threads block
How to read the flame graph it produces:
- Width is time. The widest plateaus are where your milliseconds actually go. Against our lab app, you'd expect
ProdMystery.lambda$main$0— the spinner — as the dominant plateau, caught red-handed. - Height is call depth, not importance. A tall thin spike is a deep call chain that rarely runs; ignore it. A wide plateau near the bottom is the hot code.
- Click to zoom, and read the percentages. The interactive HTML lets you click a frame to zoom into its subtree — the standard workflow is: find the widest plateau, zoom, read the frame names downward to the exact line.
- Why this tool and not a dump: a profiler samples continuously with ~1% overhead and no safepoint bias (it uses
AsyncGetCallTrace), so it sees the distribution of CPU time across methods. Three dumps tell you one thread is hot; a flame graph tells you the hot method is 78% of total CPU and exactly which caller chain leads to it.
The decision rule: high CPU → profiler first, dumps second. The profiler names the hot method; the dumps confirm the hot thread's exact stack and state. And when you can't install a profiler, the poor-man's version is exactly what section 2 did — three dumps, same stack, ten seconds apart.
6. Heap dumps: what is retaining memory?
When memory grows monotonically, the question isn't "what was allocated" — it's "what is being retained". A heap histogram is the fastest way to see the shape of the heap without opening a 500MB dump file:
$ jmap -histo 22340 | head -6
num #instances #bytes class name (module)
-------------------------------------------------------
1: 9634 214312384 [B (java.base@21.0.3)
2: 16 433976 [Ljdk.internal.vm.FillerElement; (java.base@21.0.3)
3: 9335 224040 java.lang.String (java.base@21.0.3)
Line 1 is the leak, caught in one glance: 9,634 byte[] instances ([B is JVM-speak for byte array) holding 214MB — an order of magnitude more than everything else combined. The histogram answers "what kind of objects dominate the heap"; the dump answers "who is holding them". Take one:
jcmd <pid> GC.heap_dump /tmp/heap.hprof # against a live JVM
# or capture the crash itself, automatically:
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/ LeakUntilOOM
The second form is the one to set in production today — the dump from the actual crash is worth more than any post-mortem theory. Here's what it looks like when it fires, on a program that leaks 1MB at a time into a 256MB heap (real output):
$ java -Xmx256m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/p6/ LeakUntilOOM
retained ~75 MB
retained ~100 MB
retained ~125 MB
java.lang.OutOfMemoryError: Java heap space
Dumping heap to /tmp/p6/java_pid23025.hprof ...
Heap dump file created [136771943 bytes in 0.708 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at LeakUntilOOM.main(LeakUntilOOM.java:12)
Then open java_pid23025.hprof in VisualVM or Eclipse MAT and run the dominator tree, sorted by retained size. (One lab limitation, stated honestly: this machine's jmap couldn't read the dump file offline — it only works against a live PID here — so the dominator-tree step happens in a GUI tool, not the terminal. No fabricated MAT output below.) Two reading skills for that step:
- Shallow vs retained size. Shallow is the object itself; retained is everything that would be freed if it were collected. Sort by retained — that's the leak. In our lab the histogram already told us the shape (one giant pile of
byte[]), and the dominator tree would show the staticLEAKlist as the single dominator. - Path to GC root. The leak isn't the
byte[]; it's the staticLEAKlist holding them. The path-from-GC-root tells you who's holding on — and who's holding on is the fix. A static collection, a forgotten listener list, a cache without eviction: the path names the culprit.
The decision rule: memory growth → histogram first (cheap), dump + dominator tree by retained size second. And distinguish the two OOM shapes: heap that grows until it dies (leak — the dump shows one dominator) vs heap that dies under a sudden spike (not a leak — check what allocated, e.g. an unbounded query result).
7. GC logs: the thirty-second add-on
Before the heap dump, one cheaper question: is the GC itself healthy? Turn on GC logging and read the pause lines:
$ java -Xlog:gc -Xmx256m LeakUntilOOM 2>&1 | head -4
[0.018s][info][gc] Using G1
[0.398s][info][gc] GC(0) Pause Young (Concurrent Start) (G1 Humongous Allocation) 55M->55M(126M) 4.149ms
[0.398s][info][gc] GC(1) Concurrent Mark Cycle
[0.406s][info][gc] GC(1) Pause Remark 61M->61M(126M) 0.670ms
How to read a pause line: Pause Young ... 55M->55M(126M) 4.149ms means a young-generation pause took 4.1ms, heap went 55M → 55M (nothing reclaimed — everything survived), capacity 126M. Two phrases to learn:
G1 Humongous Allocation— an object bigger than half a G1 region (our 1MBbyte[]chunks) goes straight to a humongous region. A leak of 1MB arrays shows up as a stream of humongous allocations. The GC log was already whispering "big byte arrays" before we ever ranjmap.55M->55M(nothing reclaimed) — when the heap doesn't shrink after full GCs, that's the signature of a leak rather than a tuning problem. Don't tune the collector; find the retainer (section 6).
The decision rule: long GC pauses → -Xlog:gc for pause times and causes; heap that survives full GCs → heap dump. GC logs are nearly free in production — there's little reason not to have them always on.
8. JFR: the flight recorder you should have had running
JDK Flight Recorder is the always-on profiler built into the JVM — near-zero overhead, recording method samples, allocations, lock contention, GC events, socket I/O and more into a rolling file. Dumps and profilers diagnose the present; JFR lets you time-travel to when the symptoms began.
You can drive it two ways. From the command line, start a recording that dumps when the JVM exits:
java -XX:StartFlightRecording=disk=true,dumponexit=true,filename=app.jfr,... MyAppOr in-process with the jdk.jfr API — which also lets you read the recording back programmatically. This program records 15 seconds of a mixed workload (a CPU burner, a churny allocator, a contended lock), then prints its own summary — every number below is real output from the run:
import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordingFile;
// ... workload: burner thread + allocator thread + lock holder/waiter ...
Recording rec = new Recording();
rec.enable("jdk.ExecutionSample").withPeriod(Duration.ofMillis(20));
rec.enable("jdk.ObjectAllocationInNewTLAB");
rec.enable("jdk.JavaMonitorEnter");
rec.enable("jdk.GarbageCollection");
rec.start();
// ... run the workload for ~14s ...
rec.stop();
rec.dump(Path.of("/tmp/p6/lab.jfr"));
// ... read it back with new RecordingFile(path), count by event type ...
$ java -Xmx128m JfrLab
== JFR summary of lab.jfr ==
jdk.ExecutionSample events : 72
Top sampled top-frames:
java.util.Arrays.copyOf 63
JfrLab.lambda$main$2 5
JfrLab.lambda$main$3 4
jdk.ObjectAllocationInNewTLAB : 43186 events, ~21758715 KB allocated in new TLABs
jdk.JavaMonitorEnter : 1 (threads blocked >20ms entering a monitor)
jdk.GarbageCollection : 303 collections
Read it like an investigator, and notice what it doesn't say:
- The top sampled frame is
Arrays.copyOf, not the burner. The allocator thread kept growing anArrayListpast capacity, and every growth copies the backing array — 63 of 72 samples landed there. The "CPU hot spot" was allocation churn, not arithmetic. This is exactly the kind of misattribution JFR corrects: you'd have blamed the burner; the recorder shows the copier. - 43,186 TLAB allocations totaling ~21 GB in 14 seconds (with a 128MB heap) — and 303 young collections to show for it. Allocation rate is a first-class metric; this workload was drowning in its own garbage.
- One
JavaMonitorEnterevent — but look at its duration. ThejfrCLI prints any event in the file, so let's see the whole thing:
$ jfr print --events jdk.JavaMonitorEnter lab.jfr
jdk.JavaMonitorEnter {
startTime = 04:30:38.488 (2026-10-06)
duration = 3.92 s
monitorClass = java.lang.Object (classLoader = bootstrap)
previousOwner = "lock-holder" (javaThreadId = 23)
address = 0x767C6C002C60
eventThread = "lock-waiter" (javaThreadId = 24)
stackTrace = [
JfrLab.lambda$main$1() line: 34
java.lang.Thread.run() line: 1583
]
}
The waiter blocked 3.92 seconds entering a monitor whose holder only ever slept 250ms at a time. Why so long? The holder thread itself was starved — on this small 2-core lab box, the burner plus the GC storm (303 collections!) left little CPU for the lock holder, stretching every hold. That's a genuine production lesson hiding in a lab artifact: lock hold times are not just your code — they're your code plus scheduling. Under CPU saturation, contention multiplies. (And note the event only fires for blocks longer than its 20ms threshold — brief contention is deliberately invisible.)
Isolate the suspect to confirm the mechanism — 6 seconds of pure burn, nothing else running:
$ javac JfrBurn.java && java JfrBurn
jdk.ExecutionSample events in 6s of pure burn: 9
JfrBurn.lambda$main$0 9
9 out of 9 samples on the burner's lambda — the attribution is perfect. But 9 samples in 6 seconds, against a configured 20ms period (which should yield ~300)? An honest caveat: on this small shared container, the sampler delivered far fewer events than configured — I measured ~1.5/sec instead of ~50/sec, and I'm not going to theorize about exactly which layer throttled it. The attribution mechanism is proven by the run; the rate is environment-dependent. On real server hardware you get the full configured cadence, which is what makes JFR's method sampling a production-grade profiler. The jfr summary CLI cross-checks any recording independently:
$ jfr summary lab.jfr
Version: 2.1
Chunks: 1
Start: 2026-10-06 04:30:38 (UTC)
Duration: 14 s
Event Type Count Size (bytes)
=============================================================
jdk.ObjectAllocationInNewTLAB 43186 690934
jdk.GarbageCollection 303 6856
jdk.ExecutionSample 72 720
jdk.JavaMonitorEnter 1 24
...
The decision rule: JFR is the tool you configure before the incident. A continuous recording (disk=true, rolling buffer) means the 2 AM page starts with "open the recording, rewind to 1:47 AM" instead of "reproduce it". Open .jfr files in JDK Mission Control for the full GUI; the CLI (jfr summary, jfr print) covers triage.
9. The diagnosis walkthrough: back to 2 AM
Return to the opening scenario — p99 from 150ms to 3s, CPU pinned at 95% — and run the decision tree. Each step takes one command and rules something out:
Step 1: Is it CPU or waiting? One thread dump. If the request threads are RUNNABLE in application code → CPU problem, go to step 2. If they're BLOCKED/WAITING → contention or deadlock, read the deadlock section first (section 2 showed you exactly what it looks like).
Step 2: Who eats the CPU? Start a 30-second async-profiler CPU capture (or JFR method sampling — section 8 proved it works). Read width as time; the widest plateau is the hot method. In our lab that's the spinner's lambda — in yours it might be a regex, a serialization loop, or a chatty encryption call.
Step 3: Is memory growing too? jmap -histo takes seconds and needs no dump file. One dominant class (our 214MB of byte[]) → heap dump + dominator tree by retained size → path to GC root → the holder, which is the fix.
Step 4: When did it start? If you have a continuous JFR recording, rewind. "Lock contention spiked 20 minutes before CPU did" and "GC pauses grew over two hours" are sentences you can only utter with a recorder running. If you don't have one — this incident is the argument for turning it on.
And the symptom → tool map, one last time, as the version to memorize:
- High CPU, slow responses → async-profiler flame graph (or JFR sampling); thread dumps to confirm the hot stack. Three dumps, same stack, ten seconds apart.
- Memory growth / OOM →
jmap -histofirst; heap dump + dominator tree by retained size;HeapDumpOnOutOfMemoryErroralways on in prod. - Hangs, CPU idle → thread dump; read the JVM's
Found one Java-level deadlocksection before anything else. - Long GC pauses →
-Xlog:gcfor pause times and causes; heap dump if the heap survives full GCs (that's a leak, not a tuning problem). - "It started at 2 AM and I don't know why" → the JFR recording from before the incident — which means configuring it now.
What's next
You've now got the diagnosis half of production Java: when the JVM misbehaves, you know which of the four questions to ask and which tool answers it. The whole Concurrency & JVM track in six lines:
- Threads, Locks & Shared State — race conditions, visibility, atomicity;
synchronized,volatile,ReentrantLock; deadlock as lock-ordering. - Executors & Thread Pools — sizing the old world: pool sizes, queues, and rejection when work outruns workers.
- Virtual Threads — one per task; virtual threads remove thread scarcity, not resource scarcity.
- CompletableFuture — async pipelines without callback hell.
- JVM Memory & Garbage Collection — heap, stack, metaspace; generational collection; diagnose before you tune.
- Production Diagnosis (this post) — thread dumps show where threads are, profilers show who's busy, heap dumps show what's retained, JFR shows what happened before.
Diagnosis tells you what's wrong right now. The next track — Production Java — is about not getting paged at all: observability (logs, metrics, traces), configuration and secrets, resilience (timeouts, retries, circuit breakers), safe deployments, load testing, and a capstone production-ready service that pulls the whole roadmap together.
Field check before you move on: reproduce the lab above on your own machine — run ProdMystery, then (1) take three jstack dumps five seconds apart and find the one stack that never moves; (2) locate the Found one Java-level deadlock section and name both threads and both locks from it; (3) run jmap -histo and identify the single class dominating the heap, in bytes; (4) write a 20-line program that starts an in-process JFR Recording around any workload you choose, then prints the count of jdk.ExecutionSample events and the top three sampled methods — bring that summary to the Production Java track, where observability starts with measuring. If your sampler delivers far fewer events than the configured period (as mine did on a small container), note the rate alongside the attribution: the mechanism is what you're learning; the rate is the environment's.
Continue: Java Learning Roadmap 2026
Comments
Post a Comment