Sub topic 4
First look with jcmd, jstat and jstack
This chapter covers three JDK command-line tools that show what a running JVM is doing. They need no restart and no agent, so they are the cheapest way to learn what is wrong before you reach for a profiler. It assumes you can run Java from a shell, know what a heap and a thread are, and can read a stack trace. Garbage collection and JIT concepts from the previous chapter help but are not required.
What each tool is for
All three tools attach to a live JVM by process ID (PID). They differ in what they report.
| Tool | What it gives you | Typical question |
|---|---|---|
| `jcmd` | A general command channel: flags, uptime, heap info, thread dumps, heap dumps, JFR control | "What is this JVM and how is it configured?" |
| `jstat` | Numbers sampled over time: memory pool usage, GC counts and times, JIT activity | "Is GC busy right now?" |
| `jstack` | A snapshot of every thread's stack | "What are the threads doing, and is anything stuck?" |
jstack <pid> does the same job as jcmd <pid> Thread.print. Prefer jcmd where you can, because one tool then covers most of your needs.
Finding the process
Run jcmd with no arguments to list the JVMs you can attach to.
jcmdEach line shows a PID and the main class or JAR. The jps tool gives a similar list. Two rules cause most attach failures:
- You must run the tool as the same user that started the target JVM (or as root).
- In a container, run the tool inside the container's PID namespace, for example with
docker exec. The PID on the host is not the PID the JVM sees for itself.
The tool's JDK version should match the target's, or be newer. A JRE-only installation does not include these tools.
Asking the JVM questions with jcmd
jcmd <pid> help lists every command the target supports. A few cover most first-look work:
jcmd <pid> VM.version
jcmd <pid> VM.uptime
jcmd <pid> VM.command_line
jcmd <pid> VM.flags
jcmd <pid> GC.heap_infoThese answer basic questions that are easy to get wrong by guessing:
- Which JDK is this?
VM.version. - Which GC is in use, and what heap limits apply?
VM.flagsshows the resolved flags, including ergonomic defaults such as the selected collector and the maximum heap size.VM.command_lineshows only what was typed. - How long has it been running?
VM.uptime. A JVM that started 90 seconds ago is probably still warming up. - How full is the heap?
GC.heap_infoprints a per-region summary.
Wrong assumptions about flags are a common source of wasted effort. A container memory limit, for instance, changes the default max heap, so check VM.flags before you theorise.
A cheap look at what fills the heap
jcmd <pid> GC.class_histogram | head -20This prints the classes with the most instances and bytes. It does not show who holds the objects, but a surprising top entry is a good lead. By default it forces a full GC first so it counts only live objects. That causes a pause, so use it with care on a busy production system.
Watching GC with jstat
jstat samples counters from the JVM's performance data. The -gcutil option shows each pool as a percent of its capacity, with GC counts and cumulative times:
jstat -gcutil <pid> 1000 10The 1000 is the sampling interval in milliseconds and 10 is the number of samples. Without the last number it runs until you stop it. The columns, on JDK 11 and later, are:
| Column | Meaning |
|---|---|
| S0, S1 | Survivor spaces, percent used |
| E | Eden (new objects), percent used |
| O | Old generation, percent used |
| M, CCS | Metaspace and compressed class space, percent used |
| YGC, YGCT | Young collection count and total seconds |
| FGC, FGCT | Full collection count and total seconds |
| CGC, CGCT | Concurrent collection count and total seconds |
| GCT | Total GC seconds |
Read it as a time series, not a single row. Watch these patterns:
- E climbs to near 100%, then drops while YGC goes up by one. This is normal. How fast E fills tells you your allocation rate.
- YGC rises several times per second. Allocation is heavy. That is the subject of the allocation chapter.
- O rises after each collection and never falls, and FGC keeps growing. Objects are surviving when they should not. This points to a leak or an undersized old generation.
- GCT grows by a large fraction of elapsed wall time. If GCT rises by 0.3 s every second, the JVM spends 30% of its time collecting.
jstat -gc shows absolute capacities and usage in KB instead of percentages. Use it when you need real sizes.
Note that jstat does not accept every collector's detail in the same way. With G1 or ZGC, the pool columns are coarser than with the older Parallel collector, so use GC logs (next chapter) for finer detail.
Taking thread dumps
A thread dump is a snapshot of every thread's name, state and stack. Capture one with:
jcmd <pid> Thread.print > threads.txtThe -l option on jstack (or Thread.print -l on jcmd) adds information about owned java.util.concurrent locks. A typical entry looks like this:
"http-worker-7" #42 prio=5 os_prio=0 cpu=1520.4ms elapsed=88.1s tid=0x00007f1c40012000 nid=0x2b4f waiting for monitor entry [0x00007f1c2e5fc000]
java.lang.Thread.State: BLOCKED (on object monitor)
at com.example.Cache.get(Cache.java:41)
- waiting to lock <0x00000007c0a1b2c8> (a com.example.Cache)
at com.example.Handler.handle(Handler.java:27)The thread states you will see are these:
RUNNABLE: running, or ready to run, or in native code such as a socket read. A thread blocked on I/O can still show asRUNNABLE.BLOCKED: waiting to enter asynchronizedblock that another thread holds.WAITINGandTIMED_WAITING: parked onwait,park,sleepor a lock fromjava.util.concurrent. Idle pool threads usually look like this and are not a problem.
At the bottom of a dump the JVM reports any Found one Java-level deadlock, with the threads and locks involved. That check covers only monitors and ownable synchronizers, so use -l to include them.
One dump is a photograph, several are a film
A single dump can mislead because a thread may happen to be somewhere briefly. Take three dumps five to ten seconds apart and compare. A thread that sits at the same line in all three is a real suspect. If 40 threads are BLOCKED waiting for the same lock address, you have found contention without any profiler.
Taking a heap dump
When memory use looks wrong, a heap dump records every live object:
jcmd <pid> GC.heap_dump /tmp/heap.hprofThe target JVM writes the file, on its own filesystem, so the path must exist and be writable there. The dump pauses the application, and the file is about as large as the used heap. Check free disk space first. Analysing the dump is covered in a later chapter.
A triage sequence
The diagram shows the order I use for a first look at a slow service.
Limits and cautions
- These tools give snapshots and counters, not cause. They tell you which category of problem you have, then you choose the next tool.
- Thread dumps and heap dumps bring the JVM to a safepoint, a point where all threads pause. A large heap dump can stall a service for seconds.
- Attach can be disabled with
-XX:+DisableAttachMechanism. If so, none of this works and you must plan for it in advance. - Do not run
jstatevery 10 ms. A 1000 ms interval is plenty and keeps the overhead low.
Exercise
A service shows these jstat -gcutil samples, one per second: O goes 71, 73, 75, 77, 79 and FGC stays at 2 and does not change. E repeatedly climbs to 100 and falls back, with YGC rising by one each time. Is this a leak, and what would you check next?
Show answer
Not yet conclusive. The old generation is growing steadily, but no full collection has run, so some of that data may be garbage that the old generation has not had a reason to collect yet. A leak shows as O staying high after a full collection. Keep sampling until FGC increases (or force a check with GC.classhistogram, accepting the full GC it triggers) and see whether O falls back. If it stays high and keeps rising after each full GC, take a heap dump with GC.heapdump and find what holds the objects.
Exercise
You take three jcmd Thread.print dumps ten seconds apart. In each, 35 threads show BLOCKED with "waiting to lock <0x00000007c0a1b2c8>". What do you look for next, and why?
Show answer
Search the dump for the thread that holds that same address ("locked <0x00000007c0a1b2c8>"). Its stack shows what work it is doing while holding the lock, which is what the other 35 threads are waiting on. If it is doing slow I/O or a long computation inside the synchronized block, shorten the critical section or change the locking strategy, then re-measure.