Lesson · JVM Internals
The JVM toolbelt: jps, jcmd, jstat, jmap, jstack, JFR
17 min readDiagnostics & Tooling
A slow service, a process id, and nothing instrumented: the JDK already ships the tools that answer the next five questions. Which JVMs exist, how they were started, what the threads are doing, where the memory went, and what the collector has been up to. This lesson is the order to reach for them.
A slow service and a process id
The endpoint is slow, the host is busy, and all you have is a process id. Nothing was instrumented, no agent was installed, and restarting the JVM to add flags would throw the evidence away.
Every JDK (the developer distribution: the JVM, the core class libraries, and one bin directory of tools) ships small tools that attach to a running JVM from the outside: list processes, print flags, dump threads and heaps, record events. The first question is which JVMs are actually on this machine, and jps answers it in one line.
jps -lvm 4711 app.jar --server.port=8080 -Xmx2g -Dspring.profiles.active=prod 4830 jps -lvm
The toolbelt ships with the JDK you compile with: the same bin directory that has javac has jcmd and friends, and none of them needs the target process to be restarted.
jcmd: the one command to learn first
jcmd began as a way to send diagnostic commands to a JVM and now fronts almost everything the older tools do. Run it with no arguments and it lists the running JVMs; run jcmd <pid> help and it prints the commands this particular JVM supports right now.
That help output is the index. A handful of entries cover most incidents:
- `VM.command_line` and `VM.flags -all`: how the process was really started, and what every flag ended up as.
- `Thread.print`: every thread with its stack, the same content as jstack, plus
-lfor java.util.concurrent locks. - `GC.heap_info`: current heap capacity and occupancy per region: the cheapest way to see whether memory is the problem at all.
- `GC.class_histogram`: the heap grouped by class, counts and sizes, the quickest who-is-the-heap answer.
- `GC.heap_dump`: a full HPROF dump. It runs a collection first unless you pass
-all, so treat it as a pause-producing command. - `JFR.start`, `JFR.dump`, `JFR.check`, `JFR.stop`: recording control, covered further down.
- `VM.metaspace`, `VM.native_memory`, `VM.classloaders`: for the memory that is not your heap (runtime-memory has the layout).
jcmd is the one command to learn first: it fronts almost everything, and `jcmd <pid> help` is the index.
Toolbelt map · one area each
four areas, four first tools, one index in front of themjcmd <pid> help
The index: every area below answers through this one command, and it lists what this JVM supports.
Pick the area the symptom points at
Threads
What every thread is doing, and which locks it holds or waits for.
The process is hung, or burning CPU with no obvious work happening.
Heap
What is held, by class first, then by retaining path in an analyser.
Memory grows, or the floor after full collections keeps climbing.
GC
Frequency, capacity and pause time: whether collection is the complaint.
Pauses or latency are the symptom and you need them measured over time.
Whole VM
Everything at once: recorded for later, or polled every minute as metrics.
You do not know which area yet, or the incident already happened.
Every tool here ships with the JDK and attaches from outside the process. When a process does not show up, the usual reason is the user account or the namespace it runs in, not a missing tool.
Two dumps you will take more than any other
A thread dump is a photograph of every thread: state, stack, and every lock it holds or waits for. A heap dump is a photograph of every surviving object, with enough reference data to rebuild the graph. One answers what the process is doing, the other what it is holding.
Monitor cycles between threads are the deadlock lesson's subject. Here is the operational half: which command takes each one, and what it costs.
| What you want | Modern invocation | Legacy name | Cost |
|---|---|---|---|
| Every thread and its stack | jcmd <pid> Thread.print | jstack <pid> | medium: it stalls nothing |
| Plus java.util.concurrent locks | jcmd <pid> Thread.print -l | jstack -l <pid> | the same, with more output |
| Heap grouped by class | jcmd <pid> GC.class_histogram | jmap -histo (:live counts after a collection) | high: it walks the whole heap |
| Every live object (HPROF) | jcmd <pid> GC.heap_dump file.hprof | jmap -dump:live,format=b,file=file.hprof | highest: a collection, then the write |
A heap dump costs a collection and disk; a thread dump costs nothing. Take the cheap one first, twice, before you pay for the expensive one.
jstat: capacity and pause over time
One sample of anything is a coincidence. jstat -gcutil <pid> 1000 prints a row every second: the percentage used in each space, plus the counters for young and full collections.
The counters are cumulative, so the numbers that matter are deltas between rows. Watch the old region percentage settle after each full collection: a floor that stays put is healthy allocation, a floor that climbs is a live set that is growing. gc-debugging takes that reading further.
jstat -gcutil 4711 1000 S0 S1 E O M CCS YGC YGCT FGC FGCT GCT 0.00 62.11 44.19 38.42 95.62 89.14 214 1.842 3 0.312 2.154 63.44 0.00 12.08 38.44 95.62 89.14 215 1.847 3 0.312 2.159 # E: young usage % O: old usage % YGC / FGC: collection counts # YGCT / FGCT / GCT: accumulated times, so a pause is the delta between two rows
- `-gcutil`: percentages plus counters, the right screen for a live incident.
- `-gc`: the same moments with capacities and usage in kilobytes when percentages are not enough.
- `-gccause`: adds the cause of the last and current collection when no log is configured.
- Read it as a screen, not an API: the JDK marks jstat experimental and warns that its format can change between releases.
jstat tells you that collection pressure is rising; it never tells you who is responsible. That is the dump's job.
Flags: decoding who set the value
-XX:+PrintFlagsFinal prints every flag the JVM knows, at the value it actually took, tagged with its category and where the value came from. That second tag is the part nothing else shows: default, ergonomic (the JVM chose it), or the command line.
Some flags are hidden from the default view. Diagnostic flags need -XX:+UnlockDiagnosticVMOptions first, experimental ones need -XX:+UnlockExperimentalVMOptions, and the unlock line has to come before the flag it unlocks.
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintFlagsFinal -version | grep -i -e MaxHeap -e UseG1GC # size_t MaxHeapSize = 4294967296 {product} {ergonomic} # bool UseG1GC = true {product} {ergonomic} # uint TargetSurvivorRatio = 50 {product} {default} # the first brace is the flag category, the second says where the value came from jcmd 4711 VM.flags -all # the same list from outside, no restart jinfo -flag MaxHeapSize 4711 # one flag; -flags prints the command line only
The origin tag answers the question you actually have: not what the value is, but who set it.
JFR: record first, analyse second
Java Flight Recorder samples the JVM from the inside: allocations, GC pauses, thread parks, lock waits, I/O and more, written to a file that can be replayed after the incident. It was a commercial feature until JDK 11 open-sourced it (JEP 328), and since JDK 14 its events can be streamed live (JEP 349).
A recording can start with the process (-XX:StartFlightRecording) or on demand (jcmd <pid> JFR.start), and it can run continuously with a bounded size. Two profiles ship with the JDK: default targets continuous, low-overhead recording, while profile collects more detail for short captures.
# at start-up: bounded, written on exit java -XX:StartFlightRecording=filename=app.jfr,duration=120s,settings=profile -jar app.jar # on a running JVM: start, snapshot, stop jcmd 4711 JFR.start name=incident duration=60s filename=incident.jfr jcmd 4711 JFR.dump name=incident filename=now.jfr # write the buffer, keep recording jcmd 4711 JFR.check # what is recording right now # analyse: JDK Mission Control, or a first pass from the command line jfr summary incident.jfr jfr print --events jdk.ThreadPark incident.jfr
- Allocation samples: where objects are being created, sampled rather than exhaustive, which is how the overhead stays low.
- GC pauses with their causes: every collection, its duration and its trigger, on one timeline.
- Thread parks and monitor waits: why threads are not running, which is often the latency no CPU profile can see.
- Virtual thread pinning: JDK 21 and later record
jdk.VirtualThreadPinnedwhen a virtual thread cannot unmount, the diagnostics trail the virtual-threads part of the course asks for.
Record first, analyse second: a recording makes the JVM explain itself after the fact, and the interesting incident is always already over.
JMX: the same numbers as a metric endpoint
jcmd answers a human at a shell. JMX exposes the same internals as MBeans so a dashboard can poll them every minute. The platform MBean server is inside every JVM, and the standard beans already cover most Java metrics.
| Bean | Answers | Watch out |
|---|---|---|
| MemoryMXBean | heap and non-heap usage, plus gc(), which is the same request as System.gc() | one call is a snapshot, not a trend |
| GarbageCollectorMXBean | one bean per collector: collection count and accumulated collection time | counts can be -1 when a collector does not report them, so sum defensively |
| ThreadMXBean | thread counts, per-thread CPU time, and findDeadlockedThreads() for the deadlock lesson's health endpoint | total counts include threads you never created |
| BufferPoolMXBean | direct and mapped buffer memory, the area a heap dump cannot show | the pool gives you a total, not the buffer that holds it |
A tool you run once answers today's question; an MBean answers it every minute, which is what on-call actually needs.
The workbench: from symptom to first tool
Each symptom points at one area, and every area has a cheapest first move. The workbench below is that mapping: pick the symptom you actually have and it shows the command to run first, what to look for in the output, and where to go when the answer is not there.
- High CPU: thread dumps first, two of them a few seconds apart; JFR second.
- Suspected deadlock:
jstack -lorThread.print -l, with the reading in the deadlock lesson. - Memory growth:
jstat -gcutilto see whether the floor moves, then a heap dump. - Pause spikes: GC logs first, then the safepoint lines, because a pause is collection plus the wait for threads.
- Attach rules: the tools need the same effective user and an attachable process.
-XX:+DisableAttachMechanismcloses the door on purpose, and a JVM inside another container namespace is invisible from the host.
Cheapest first, always: thread dumps before heap dumps, samples before full recordings, and read the impact line jcmd prints next to every command.
Diagnostics workbench · first tool per symptom
pick the symptom you haveCPU saturation in a Java process is almost always visible in stacks. A profile is the second step, not the first.
jcmd 4711 Thread.print > td1.txt sleep 10 jcmd 4711 Thread.print > td2.txt # the frame that appears in both dumps is where time goes
what to look for
- Several threads RUNNABLE on the same stack frame: that frame is the hot loop.
- GC threads on top instead: the CPU is being spent reclaiming, so switch to the memory row.
- No repeated stack and no GC threads: record with JFR and read the method profile.
If that is not it: jcmd 4711 JFR.start name=hot duration=60s settings=profile filename=hot.jfr, then open the recording in Mission Control.
Every command here reads. GC.heap_dump is the one that collects before it writes, and none of them changes the code.
An empty jps does not mean nothing is running
jps and jcmd see only what the attach mechanism can reach: the same effective user, the same host, the same container namespace, and the mechanism itself enabled. A JVM running as another user, or inside a different container, or started with -XX:+DisableAttachMechanism, will not appear while it serves traffic perfectly well. Before concluding the process is gone, check the process list of the machine or namespace the JVM actually runs in.
Interview angles
A service is slow and you have only its process id. What do you run first?+
jcmd <pid> help shows what this JVM offers, then two Thread.print dumps ten seconds apart show where the threads are. If neither answers the question, start a 60-second JFR recording and read it in Mission Control.
The order is about cost: thread dumps and VM.flags are read-only and non-invasive, while GC.heap_dump runs a collection before it writes. An attach that is cheap enough to do twice beats one expensive action done once.
Follow-up: When would you skip straight to JFR?
jstack versus JFR for a hang: when do you reach for each?+
jstack or Thread.print is the immediate answer: one cheap snapshot that names locks and monitor cycles. JFR is the follow-up when you need history or context, because it records waits and parks as they happen instead of only at the moment you attach.
Common misconception: That a profiler is always the better tool. A profiler shows where CPU goes; a hang is usually a thread that is not running at all, which is a stack question first.
What does jstat measure, and what is the trap in its output?+
It samples per-space usage and cumulative collection counters, so a pause is the delta of YGCT or FGCT between two rows. The trap is treating the format as an interface: the JDK marks jstat experimental and warns that columns can change.
jstat reads the JVM's performance counters, so it works without a log configured and without a restart. That convenience is exactly why it is a first-look tool, and the GC log is what you keep for evidence.
A teammate wants to raise -Xmx because memory grows. What do you check first?+
Whether the floor after each full collection is moving, because a rising floor across full GCs is a growing live set and more heap only buys time. jstat -gcutil shows the floors cheaply; a heap dump in MAT names what holds the growth.
Follow-up: What if the floor is flat and pauses are the complaint?
How do you find out who set a flag you never passed?+
-XX:+PrintFlagsFinal prints every flag with tags that say where the value came from: default, ergonomics, or the command line. jcmd <pid> VM.flags -all does the same for a running JVM, and jinfo -flag prints one flag on its own.
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintFlagsFinal -version jcmd 4711 VM.flags -all jinfo -flag MaxHeapSize 4711
The heap looks healthy but the process still dies with OutOfMemoryError. What are you missing?+
Everything outside the heap: direct buffers, metaspace, thread stacks and native allocations. BufferPoolMXBean covers the first, thread counting covers the third, and runtime-memory maps the whole set so the next message points somewhere useful.
A heap dump is a heap dump, not a memory dump. That distinction becomes production-critical in gc-debugging, where the message names an area the dump does not contain.