Diagnostic tools in Java
jcmd, jstack, jmap, JDK Flight Recorder, Mission Control, heap dumps.
jcmd, the all-rounder
Run **jcmd with no arguments to list running JVMs** and their PIDs. Then pass a PID plus a command: thread dumps, heap dumps, flags, Flight Recorder. Older single-purpose tools: jstack, jmap, jstat.
jcmd # list JVMs
jcmd 4242 Thread.print # thread dump
jcmd 4242 GC.heap_dump h.hprof
jcmd 4242 VM.flagsPhoto vs inventory
A thread dump is a photo: what every thread is executing right now and which locks it holds or waits for. Perfect for deadlocks and stuck requests. A heap dump is an inventory of every object in memory. jstat prints GC statistics live.
Hanging, but idle
Requests hang and CPU is near 0%. What should you capture first?
Several thread dumps a few seconds apartA heap dumpThe output of javap
Show the answer
Low CPU plus hanging requests means threads are waiting: on locks, I/O or a pool. Take several thread dumps a few seconds apart: threads stuck at the same place in every dump reveal the real blocker.
Flight Recorder
JDK Flight Recorder (JFR) is built into the JVM and records events (allocations, locks, GC, I/O) with low enough overhead to run continuously in production. Dump a recording when something goes wrong and analyze it in JDK Mission Control.
jcmd 4242 JFR.start duration=60s \
filename=rec.jfrSorting by shallow size
In a heap dump analyzer, sorting by shallow size (the object itself) shows boring byte[] and String at the top. Sort by retained size: how much memory would be freed if that object were collected. A tiny HashMap can retain 3 GB.
An incident runbook
Hangs: several thread dumps. Memory growth: a heap dump, then retained sizes and paths to GC roots. Vague slowness: a JFR recording. Writing these commands into your team's runbook before the incident saves precious minutes during one.
Key takeaways
- jcmd <pid> Thread.print = thread dump
- jcmd <pid> GC.heap_dump file.hprof = heap dump
- JFR: low-overhead recording, analyzed in Mission Control
- Retained size shows what an object keeps alive
💡 A thread dump is a photo of what everyone is doing right now; a heap dump is an inventory of the whole warehouse.
When a thread dump finds threads deadlocked on Java monitors, it says so explicitly with a "Found one Java-level deadlock" section at the end.
Practice questions
Requests hang and CPU is near 0%. What should you capture first?
- A GC log from last week
- The output of javap
- A heap dump
- Several thread dumps a few seconds apart
Check your answer
Several thread dumps a few seconds apart. Low CPU plus hanging requests suggests threads are waiting on locks, I/O or pools. Thread dumps show exactly where they are blocked.
Which JDK command, run with no arguments, lists the running Java processes and their PIDs?
- jlink
- jcmd
- jdeps
- javap
Check your answer
jcmd. jcmd with no arguments lists local JVMs. You then pass a PID plus a command, like `jcmd 4242 Thread.print`.