Sub topic 12
Heap Dumps and Tracking Down Leaks
This chapter assumes you can read a GC log, run jcmd, and understand that the heap holds objects reachable from GC roots. It covers how to tell a leak from a large but healthy heap, how to capture a heap dump, and how to find what keeps leaked objects alive.
What a leak is in Java
Java has a garbage collector, so a "leak" does not mean forgotten free calls. A leak is a set of objects that your program no longer needs but that are still reachable from a GC root. The collector cannot reclaim reachable objects, so the live set grows until the JVM throws OutOfMemoryError or spends most of its time in GC.
GC roots include:
- Static fields of loaded classes.
- Local variables and parameters on live thread stacks.
- Active threads themselves.
- JNI references.
Typical causes:
- A static
MaporListused as a cache with no eviction. - Listeners or callbacks registered and never removed.
ThreadLocalvalues on pooled threads that never end.- Classloader leaks, where a redeployed application is kept alive by one stray reference.
- Unbounded queues between a fast producer and a slow consumer.
Confirming that it is a leak
A heap dump is expensive, so first confirm the symptom. In a GC log or jstat -gcutil <pid> 1000, look at heap occupancy after a full or mixed collection. A healthy application shows a sawtooth: usage rises, a collection drops it back to roughly the same floor. A leak shows a floor that climbs over time.
Watch for these signs:
- The post-GC floor rises across several collections.
- Full GCs become frequent and free little memory.
- The
Oldcolumn injstat -gcutilkeeps approaching 100%.
A rising floor can also be legitimate warm-up, such as a cache filling to its configured limit. Keep observing until the floor flattens or the JVM fails.
Capturing a heap dump
Use jcmd, which is the recommended tool in current JDKs.
jcmd <pid> GC.heap_dump /tmp/heap.hprofThree things to know:
- The path is written by the target JVM process, not by
jcmd, so it must be writable by that process. - By default only live objects are dumped, which forces a full GC first. Add
-allto include unreachable objects. For leak hunting the default is what you want. - The JVM pauses for the duration of the dump. For a multi-gigabyte heap this can take many seconds, and the file is roughly as large as the used heap. Check free disk space first.
To capture a dump at the moment of failure, start the JVM with these flags:
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps -jar app.jarOpening the dump
The .hprof format is read by Eclipse MAT (Memory Analyzer), VisualVM, and IntelliJ IDEA's profiler. The workflow below uses Eclipse MAT terminology. MAT needs its own heap setting (in MemoryAnalyzer.ini, -Xmx) of at least the dump's size, and often more, because it builds indexes.
Shallow size, retained size and the dominator tree
Two measures matter:
- Shallow size is the memory an object occupies by itself: its header and fields. A
HashMapobject alone is small. - Retained size is the memory that would be freed if the object were collected: the object plus everything reachable only through it.
A leaking cache has a small shallow size and a huge retained size. Sorting by shallow size will show byte[] and String at the top, which tells you little. Sort by retained size instead.
The dominator tree organizes objects so that object A dominates B if every path from a GC root to B passes through A. Top entries of the tree, ordered by retained size, are the objects whose removal would free the most memory. Start there.
| View | What it answers | When to use it |
|---|---|---|
| Histogram | Which classes have the most instances or bytes | Quick first look, spotting odd counts |
| Dominator tree | Which objects retain the most memory | Finding the owner of the bulk of the heap |
| Path to GC roots | Why a specific object is still reachable | Identifying the reference that must be cut |
| Leak suspects report | Automated guess at the biggest retainers | A fast starting point to verify, not trust |
| Comparing two dumps | Which classes grew between snapshots | Confirming growth and separating leak from baseline |
A step-by-step investigation
- Open the dump and run the leak suspects report. Note any single object retaining a large share of the heap.
- Open the histogram. Look for a class whose instance count looks wrong, for example 4 million
Sessionobjects when you have 200 users. - Right-click the suspicious class and list its objects. Pick one and choose "Path to GC Roots", excluding weak and soft references. Weak and soft references do not keep objects alive against collection, so excluding them shows the real strong chain.
- Read the chain from the root down. It typically ends at something like a static field, a
ConcurrentHashMap, an array, and then your objects. - Find the code that adds to that collection and the code that should remove from it.
A runnable leak
This program leaks by adding to a static map and never removing entries.
import java.util.HashMap;
import java.util.Map;
public class Leaky {
private static final Map<Long, byte[]> CACHE = new HashMap<>();
public static void main(String[] args) throws Exception {
long id = 0;
while (true) {
CACHE.put(id++, new byte[10_240]);
if (id % 1_000 == 0) {
Thread.sleep(10);
}
}
}
}Run it with a small heap and automatic dump, then open the result in MAT:
javac Leaky.java
java -Xmx128m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/leaky.hprof LeakyThe dominator tree shows one HashMap retaining nearly the whole heap, reached from the static field Leaky.CACHE. The byte[] objects dominate the histogram, but the map is the owner you act on.
Finding leaks without a dump: JFR
Dumps are heavy. Java Flight Recorder offers a lighter option, the OldObjectSample event. It samples objects that survive collections and, when enabled with path-to-GC-roots, records the reference chain at the end of the recording.
jcmd <pid> JFR.start name=leak settings=profile path-to-gc-roots=true
jcmd <pid> JFR.dump name=leak filename=/tmp/leak.jfr path-to-gc-roots=trueOpen the file in JDK Mission Control and look at the Memory section's old object samples. Collecting roots costs extra at dump time, so use it deliberately.
Fixing and verifying
Typical fixes match the cause:
- Replace unbounded maps with a bounded cache that evicts entries, such as one with a maximum size or time-to-live.
- Unregister listeners in a matching close or shutdown step.
- Call
ThreadLocal.remove()in afinallyblock on pooled threads. - Use bounded queues so back-pressure reaches the producer.
- Use
WeakHashMaponly when you understand that entries vanish whenever the key has no other strong reference.
After the change, repeat the earlier measurement. The post-GC floor should flatten under the same load. This follows the chapter-level rule of the whole tutorial: one change, then measure again.
Common mistakes
- Reading shallow size and blaming
Stringorbyte[]. Use retained size and follow the path to the owner. - Taking a dump of a healthy JVM and finding "suspects" that are ordinary caches.
- Dumping only once. One dump shows a state, and two dumps taken minutes apart show growth.
- Running out of disk or stalling production by dumping a very large heap without warning.
- Forgetting that the default dump forces a full GC, which is a pause you cause.
Exercise
In a heap dump, a HashMap has a shallow size of 48 bytes but a retained size of 900 MB. What does this tell you, and which MAT view and action would you use next to find out why it is still alive?
Show answer
The map holds, directly or indirectly, about 900 MB of objects that would be freed if the map were collected, so it is the owner of most of the heap. Use the dominator tree to confirm it sits near the top, then run "Path to GC Roots" (excluding weak and soft references) on the map to see which static field, thread or other root keeps it reachable. The code that fills that reference is where the fix goes.
Exercise
Your service shows a post-GC heap floor that rises by about 50 MB per hour. List three steps, in order, that you would take before changing any code.
Show answer
First, confirm with GC logs or jstat that the floor rises after full collections, not just that peak usage grows. Second, capture a heap dump (jcmd GC.heap_dump) after the growth is visible, ideally also an earlier one to compare. Third, open the dump in a memory analyzer, check the dominator tree and histogram, and use Path to GC Roots on a suspicious object to find the retaining reference.