Sub topic 12
Heap Dumps and Tracking Down Leaks
This chapter assumes you can read GC logs, run jcmd, and know the difference between live objects and garbage. A memory leak in Java means objects stay reachable from a GC root, such as a static field or a running thread, even though the program no longer needs them. The collector cannot free reachable objects, so the heap fills up.
Recognizing a leak
A leak shows up in the GC log as a rising floor. After each full or mixed collection, the used heap drops to a slightly higher level than before. Eventually the JVM throws java.lang.OutOfMemoryError: Java heap space.
Heavy allocation alone is not a leak. A high allocation rate with a flat floor after collections is GC pressure, covered in the previous chapter. A leak is a floor that climbs.
Capturing a heap dump
A heap dump is a snapshot of every object on the heap and the references between them. Take one from a running process:
jcmd <pid> GC.heap_dump /tmp/heap.hprofBy default jcmd dumps only live objects, so it forces a full GC first. To get a dump automatically when the JVM runs out of memory, add these flags at startup:
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps -jar app.jarThe file is about as large as the used heap, so check disk space first. It also contains everything in memory, including passwords and personal data, so store and share it like a secret.
Analyzing the dump
Open the .hprof file in Eclipse Memory Analyzer (MAT) or VisualVM. Work through these views in order:
- Histogram. Lists instance counts and sizes per class. Look for a class with a surprisingly large count, often
byte[],String, or one of your own types. - Shallow versus retained size. Shallow size is the memory of the object itself. Retained size is everything that would be freed if the object were collected. Sort by retained size to find the real owners.
- Dominator tree. Shows which objects keep the most memory alive. A single
HashMapretaining 800 MB is a strong suspect. - Path to GC roots. Select a suspect object and ask for the shortest path to GC roots, excluding weak references. This path names the exact field that prevents collection.
Common leak causes
- Static collections used as caches with no eviction.
- Listeners or callbacks registered but never removed.
ThreadLocalvalues in pooled threads that are never cleared.- Unbounded queues where producers outpace consumers.
- Cache keys without correct
equalsandhashCode, so entries pile up as duplicates.
import java.util.HashMap;
import java.util.Map;
public class Leaky {
private static final Map<Integer, byte[]> CACHE = new HashMap<>();
public static void main(String[] args) throws Exception {
int i = 0;
while (true) {
CACHE.put(i++, new byte[1_000_000]);
Thread.sleep(10);
}
}
}Run this with -Xmx256m -XX:+HeapDumpOnOutOfMemoryError. The dominator tree will show Leaky.CACHE retaining almost the whole heap. The fix is a bounded cache with eviction, then a re-measure of the post-GC floor.
Exercise
In MAT, an object has a shallow size of 48 bytes but a retained size of 600 MB. What does that tell you, and which view helps you find out why it stays alive?
Show answer
The object is small itself but holds references that keep 600 MB of other objects reachable, so it is a likely leak owner. Use "Path to GC roots" (excluding weak references) to see which field keeps it alive.