Sub topic 13
Diagnosing with heap dumps, jcmd, and Java Flight Recorder
This chapter assumes you know the heap layout, GC roots, the common collectors, how to read basic -Xlog output, and the OutOfMemoryError messages from earlier chapters. It also assumes you can run java and javac from a terminal. The commands target JDK 11 or later, where jcmd, jfr, and Java Flight Recorder (JFR) are all included in the OpenJDK distribution.
You will learn a repeatable way to go from "the service is slow or running out of memory" to "this class, held by this reference chain, is the cause."
A diagnostic workflow
Start cheap and get more invasive only when the cheap evidence is not enough.
- Check GC logs for the symptom: heap occupancy after each full collection keeps rising, or pauses get longer.
- Use
jcmdon the live process to look at heap occupancy and a class histogram. - Record a JFR session to see allocation, GC, and thread behavior over time.
- Capture a heap dump and analyze it to find the reference chain that keeps objects alive.
A target process to practice on
The LeakDemo from earlier fails in a second or two, which is too fast to attach tools to. This variant leaks 1 MB every 100 ms and prints its process ID.
import java.util.ArrayList;
import java.util.List;
public class SlowLeak {
private static final List<byte[]> CACHE = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
System.out.println("PID: " + ProcessHandle.current().pid());
while (true) {
CACHE.add(new byte[1024 * 1024]);
Thread.sleep(100);
}
}
}Compile it with javac SlowLeak.java. Run it in one terminal with a bounded heap, and use a second terminal for the tools:
java -Xmx256m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./dumps SlowLeakInspecting a live JVM with jcmd
jcmd sends diagnostic commands to a running JVM on the same machine, as the same user that started it. Run it with no arguments to list Java processes and their IDs. Run jcmd <pid> help to list the commands that process supports.
| Command | What it shows |
|---|---|
| `jcmd <pid> GC.heap_info` | Capacity and usage per heap region, for the active collector |
| `jcmd <pid> GC.class_histogram` | Instance count and bytes per class |
| `jcmd <pid> GC.run` | Requests a full collection, like `System.gc()` |
| `jcmd <pid> GC.heap_dump <file>` | Writes an HPROF heap dump |
| `jcmd <pid> VM.flags` | The flags the JVM is actually running with |
| `jcmd <pid> Thread.print` | A thread dump |
| `jcmd <pid> JFR.start` | Starts a Flight Recorder recording |
Class histograms
The histogram is the fastest way to see what dominates the heap:
jcmd <pid> GC.class_histogram | head -n 10The output looks like this. The numbers are illustrative, and the exact module suffix varies by JDK build.
num #instances #bytes class name (module)
-------------------------------------------------------
1: 190 199229440 [B ([email protected])
2: 6012 578112 java.lang.String ([email protected])
3: 1431 163832 java.lang.Class ([email protected])[B is the internal name for byte[]. Other array names follow the same scheme: [C is char[], [I is int[], and [Ljava.lang.Object; is Object[].
A single histogram tells you what is big. Two histograms taken minutes apart tell you what is growing. Save both to files and compare the instance counts. A class whose count rises steadily while the application is at steady load is your first suspect.
By default GC.class_histogram forces a full GC first so that only live objects are counted. Pass -all to include unreachable objects, which is useful when you want to see allocation pressure instead of the live set.
Capturing heap dumps
A heap dump is a snapshot of every object and reference in the heap, written in HPROF format. There are three common ways to get one.
- On failure.
-XX:+HeapDumpOnOutOfMemoryErrorwrites a dump the moment anOutOfMemoryError: Java heap spaceis thrown.-XX:HeapDumpPath=./dumpssets the directory or file. This is the one to enable on every production service, because the failure state is exactly what you need and you cannot reproduce it on demand. - On demand with jcmd.
jcmd <pid> GC.heap_dump /tmp/heap.hprofwrites the dump from inside the JVM. The path is resolved by the target process, not by your shell. Add the-alloption to include unreachable objects. - On demand with jmap.
jmap -dump:live,format=b,file=/tmp/heap.hprof <pid>does the same job. Thelivekeyword means a full GC first, and only reachable objects are kept.
Practical points:
- A dump is about as large as the used heap. Check free disk space before enabling the automatic dump, since a 16 GB heap can write a 16 GB file. If the dump fails to write, you lose the evidence.
- A heap dump contains everything in memory: passwords, tokens, personal data. Treat the file as sensitive, restrict permissions, and do not attach it to a public ticket.
-XX:+HeapDumpOnOutOfMemoryErrorapplies to heap exhaustion. It does not fire for a native memory failure such asunable to create native thread.- Pair the dump flag with
-XX:+ExitOnOutOfMemoryErrorwhen a supervisor such as systemd or Kubernetes will restart the process. Otherwise a JVM that has thrownOutOfMemoryErrorin one thread can keep running in a damaged state.
Analyzing a dump
Open the .hprof file in Eclipse Memory Analyzer (MAT) or VisualVM. Both parse the file and compute the same core numbers.
- Shallow size is the memory of the object itself, without anything it references.
- Retained size is the memory that would be freed if this object were collected. It includes objects reachable only through it.
- Dominator tree lists objects by retained size. An object dominates another if every path from a GC root to the second passes through the first.
- Path to GC roots shows the reference chain that keeps an object alive. Exclude weak and soft references when asking for it, since those do not prevent collection.
For SlowLeak, the dominator tree shows one ArrayList whose retained size is nearly the entire heap. Its path to GC roots ends at a static field of class SlowLeak. The chain reads: class SlowLeak (a GC root) → static field CACHE → ArrayList → Object[] → many byte[]. You fix the leak by bounding or evicting entries from CACHE, not by enlarging the heap.
In real applications the dominator is usually a framework object: a ConcurrentHashMap used as a cache, a ThreadLocal map on a pooled thread, a listener list, or a class loader that was never released. The path to GC roots names the owner, and the owner points you to the code that needs an eviction or removal.
Java Flight Recorder
JFR is a low-overhead event recorder built into the JVM. It records GC phases and pauses, allocation samples, thread states, lock contention, I/O, JIT compilation, and more, and it is designed to be safe to run in production. The default settings target roughly 1% overhead or less. The profile settings collect more detail at somewhat higher cost.
Starting a recording
At startup:
java -Xmx256m -XX:StartFlightRecording=duration=60s,filename=rec.jfr,settings=profile SlowLeakOn a running process:
jcmd <pid> JFR.start name=leak settings=profile duration=60s filename=/tmp/rec.jfr
jcmd <pid> JFR.check
jcmd <pid> JFR.dump name=leak filename=/tmp/rec-now.jfr
jcmd <pid> JFR.stop name=leakJFR.dump writes the data collected so far without ending the recording. This is useful for a continuous recording: start one with no duration and a maxage such as maxage=1h, and the JVM keeps a rolling window. When something goes wrong, you dump the last hour.
Reading a recording
Open the .jfr file in JDK Mission Control (a separate download from the JDK since version 9), or use the jfr command-line tool bundled with the JDK:
jfr summary rec.jfr
jfr print --events jdk.GarbageCollection rec.jfr
jfr print --events jdk.ObjectAllocationSample rec.jfr
jfr print --events jdk.GCHeapSummary rec.jfr| Event | Question it answers |
|---|---|
| `jdk.GarbageCollection` | Which collections ran, how long did each pause last, and why did it start |
| `jdk.GCHeapSummary` | How much heap was used before and after each collection |
| `jdk.ObjectAllocationSample` | Which classes and stack traces allocate the most |
| `jdk.OldObjectSample` | Which objects have survived long enough to be leak candidates |
| `jdk.JavaMonitorEnter` | Where threads wait on locks |
jdk.OldObjectSample is the leak-hunting event. Enabling path-to-GC-roots collection makes it record the reference chain for sampled long-lived objects, which gives you MAT-style information without a full dump. In JDK 11 you enable it with path-to-gc-roots=true on the recording options. This adds overhead, so use it for a bounded investigation.
JFR answers a different question than a heap dump. A dump is a still photo of what is reachable now. A recording is a film of what the JVM did over time. Use the dump for "what holds this memory," and JFR for "when did it start growing, and what code was allocating."
Common mistakes
- Reading a histogram taken right after a GC and a histogram taken before as if they were comparable. Use the same options each time.
- Enlarging
-Xmxto "fix" a leak. This delays the failure and makes the eventual dump larger. - Analyzing a dump taken at the wrong moment. For a leak, the dump near the point of failure is the useful one. For a slow-memory-growth question, take two dumps hours apart and compare the dominators.
- Forgetting that
jcmdonly attaches to processes of the same user, and inside a container it must run in the same container or with a shared process namespace. - Treating a
WeakReference-heavy structure as a leak. Use the "exclude weak/soft references" option when asking for paths to roots.
Exercise
A service throws OutOfMemoryError: Java heap space every few days and is restarted by its supervisor, which leaves no trace. Which JVM flags would you add so the next failure is diagnosable, and what two views would you then use in a heap dump analyzer to find the cause?
Show answer
Add -XX:+HeapDumpOnOutOfMemoryError and -XX:HeapDumpPath=<directory with enough free space>, and keep -XX:+ExitOnOutOfMemoryError so the supervisor restarts the process after the dump is written. Optionally add a rolling JFR recording with -XX:StartFlightRecording=maxage=1h,... and -Xlog:gc*:file=gc.log for context. In the analyzer, open the dominator tree to find the objects with the largest retained size, then run "path to GC roots" (excluding weak and soft references) on the suspect to see which static field, thread, or class loader holds it.
Exercise
What is the difference between shallow size and retained size, and why does a dominator tree sort by retained size?
Show answer
Shallow size is the memory used by the object itself. Retained size is the memory that would be freed if the object were collected, including objects reachable only through it. A small ArrayList object can have a tiny shallow size and a huge retained size. Sorting by retained size puts the objects whose removal frees the most memory at the top, which is where a leak almost always shows up.