A rising old-generation line is not proof of a memory leak. It might mean the heap is too small, or that traffic grew, or that a full collection has not run yet. This tutorial works through a Java memory leak heap dump investigation on a small notification service whose heap climbs until it throws OutOfMemoryError: confirm the leak from GC logs, capture a live heap dump with jcmd, use Eclipse Memory Analyzer (MAT) to find the retaining reference, then fix it and prove the post-collection floor is flat.

The commands target JDK 21 and later, where jcmd and unified logging are the supported tools. The sample service keeps a static response cache and runs on a four-thread executor. The numbers are illustrative, but the sequence is the one to use on a real incident.

Table of Contents

  • Step 1: Prove the Leak Before You Dump
  • Step 2: Capture a Live Heap Dump Safely
  • Step 3: Find the Retaining Reference in Eclipse MAT
  • Step 4: Fix the Reference and Verify the Floor
  • Presenting the Investigation in an Interview
  • Conclusion

Step 1: Prove the Leak Before You Dump

A heap dump is expensive to take and expensive to analyze. Before you interrupt a production node, establish that the problem is retention rather than sizing.

Read the post-collection floor

Start the service with a GC log that captures full collections and phase timing:

java -Xms2g -Xmx2g \ -Xlog:gc*,gc+phases=debug:file=/var/log/app/gc.log:time,uptime,level,tags \ -jar notification-service.jar 

The log records the heap occupancy before and after each pause. Ignore the sawtooth between collections and read only the value after a full GC. Oracle's Java troubleshooting guide defines this as the live set and recommends watching it after the application reaches a steady state under stable load; a live set that keeps climbing is a strong leak signal. The same guide shows how full-GC lines expose a heap that cannot reclaim space.

Here is a trimmed log from the sample service:

[412.884s][info][gc] GC(812) Pause Full (G1 Compaction Pause) 1843M->1712M(2048M) 812.441ms [1187.552s][info][gc] GC(1104) Pause Full (G1 Compaction Pause) 1962M->1868M(2048M) 866.120ms [2244.019s][info][gc] GC(1502) Pause Full (G1 Compaction Pause) 2038M->1954M(2048M) 921.773ms [3641.107s][info][gc] GC(1904) Pause Full (G1 Compaction Pause) 2041M->1998M(2048M) 902.117ms 

After each full collection the floor moves from 1712 MB to 1868 MB to 1954 MB to 1998 MB. Traffic is flat. That slope is the leak rate. Plot the post-GC value over time in a spreadsheet; the sawtooth pattern hides growth, while the floor does not.

A flat high floor is not a leak

If the post-GC line is high but flat, you have a sizing or headroom problem, not retention. The application may simply need a larger -Xmx, or need fewer full collections during traffic peaks. Oracle makes the same distinction: an OutOfMemoryError does not necessarily imply a leak, because the heap may be too small for the workload.

A useful rule of thumb:

  • Floor climbs under steady load — suspect retention. Continue to Step 2.
  • Floor is flat but close to the ceiling — tune the heap or reduce allocation pressure.
  • Floor jumps once and stays — look for a new cache, a batch job, or a deployment that changed the working set.

For later comparison, also capture a histogram at the same point in the load cycle:

jcmd 4242 GC.class_histogram | head -30 

Two histograms taken an hour apart are often enough to show which class is accumulating before you take a full dump.

Step 2: Capture a Live Heap Dump Safely

A heap dump is a snapshot of objects, fields, references, classes, GC roots, and thread stacks at one instant. Eclipse MAT's heap-dump documentation notes that it does not contain allocation history, so the dump will tell you who retains an object, not who created it. That distinction shapes the whole analysis.

Pre-flight checks

Run through this list before touching the production node:

Check Why it matters
jcmd -l shows the target PID Avoid dumping the wrong JVM when several run on the host
Free space on the dump volume An uncompressed HPROF is roughly the live-set size; leave headroom for copies and archival
Directory writable by the JVM's OS user Run jcmd as the JVM's OS user (or root); the target JVM writes the file with its own credentials
Pause budget agreed The JVM must walk the heap; Oracle rates GC.heap_dump impact as High and dependent on heap size and content
Node drained from the load balancer Prevents timeouts while the dump is written
Restricted storage Dumps contain customer data, tokens, and other in-memory secrets

Use an absolute path. A relative path is resolved by the target JVM, not by your shell, so it can land in an unexpected working directory.

Trigger the dump

jcmd 4242 GC.heap_dump -gz=1 /dumps/notification-20261129-1015.hprof.gz 

The jcmd reference documents -gz for gzip compression, with level 1 recommended as the fastest, and -overwrite for replacing an existing file. Do not use -overwrite on an incident dump unless you are deliberately repeating a capture.

Do not add -all. Without it, jcmd requests a full collection first, so the dump contains only live objects. With -all, the full collection is skipped and unreachable garbage is written too, making the file larger and adding noise to class histograms. For leak work, live-only is what you want.

The command prints the file size and the time taken when it finishes. Record both in the incident timeline, then copy the dump to the analysis host and restrict access:

chmod 600 /dumps/notification-20261129-1015.hprof.gz 

If the service is prone to running out of memory before anyone can attach, add this to the startup command so the next failure leaves evidence:

java -XX:+HeapDumpOnOutOfMemoryError -jar notification-service.jar 

Make sure the default dump location has enough space. An automatic dump taken at the moment of failure is often more valuable than a manual dump taken after a restart.

Step 3: Find the Retaining Reference in Eclipse MAT

Open the dump in Eclipse MAT; it reads the gzipped HPROF directly. The Overview page gives the total heap and the biggest consumers; the real work starts with the reports and queries.

Start with Leak Suspects

Run Leak Suspects from the toolbar. MAT's Leak Suspects report automates the first pass: it starts from the dominator tree, examines the biggest items, and flags an item that retains a significant share of the heap, with a default threshold of 10 percent. It also handles the second case, where no single object is huge but many instances of one class together retain a large amount of memory.

On the sample dump, the report names one suspect: the ResponseCache class and its ConcurrentHashMap, retaining about 1.5 GB of a 2 GB heap. That is enough to justify drilling down, but the report is a pointer, not a diagnosis. The next two views turn it into evidence.

Confirm with the Dominator Tree

Open the Dominator Tree and sort or scan by retained heap. MAT's explanation of the dominator tree defines an object as dominating another when every path from the GC root to the second object passes through the first; the retained set of an object is everything that would become collectable if that object were released. In practical terms, retained heap answers: how much memory would this object free if it disappeared?

Look for an accumulation point: an object whose retained size is much larger than the retained size of any single child. That gap means many small objects are hanging off one structure. In the sample:

Object Retained heap Interpretation
ResponseCache.CACHE (static field) ~1.5 GB The cache as a whole
ConcurrentHashMap table ~1.4 GB The map's internal node array
byte[] instances ~1.3 GB Cached response bodies

The tree takes you from "the heap is full" to "this map owns most of it." It still does not prove why the map is reachable. That is the job of the next query.

Prove it with Path to GC Roots

Right-click the suspect object and choose Path to GC Roots, then the variant that excludes weak and soft references. The Path to GC Roots inspection supports excluding fields such as weak or soft referents. MAT's leak-suspect analysis goes further and ignores weak, soft, phantom, and finalizer references when it looks for paths. This matters: a path through a WeakReference does not show a strong retention chain, and following it will send you to the wrong fix.

Read the resulting chain from the object upward, not from the root downward. In the sample it looks like this:

byte[] <- ConcurrentHashMap$Node.val <- ConcurrentHashMap$Node <- ConcurrentHashMap.table <- ResponseCache.CACHE <- static field of com.example.notification.ResponseCache <- GC root: system class 

That chain is the proof. A static final map holds every cached body for the lifetime of the class loader. Nothing evicts entries, so the map grows with the number of distinct responses until the heap is exhausted. The leak is not in ConcurrentHashMap; it is in the policy that never removes anything.

If the path instead runs through a thread, inspect the thread's stack and local variables before assuming a ThreadLocal problem. If it runs through a listener list, look for a registration without a matching removal. Both patterns are common and both are visible in the same way: the object is reachable from a GC root through a container that the application never cleans up.

Step 4: Fix the Reference and Verify the Floor

The fix should remove the unbounded retention, not just make the symptom less frequent.

Fix the unbounded static cache

The leaking version is small enough to miss in review:

public final class ResponseCache { private static final Map<String, byte[]> CACHE = new ConcurrentHashMap<>(); public static byte[] get(String key) { return CACHE.computeIfAbsent(key, ResponseCache::load); } } 

A bounded least-recently-used map is enough for a low-throughput service:

public final class ResponseCache { private static final int MAX_ENTRIES = 10_000; private static final Map<String, byte[]> CACHE = new LinkedHashMap<>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<String, byte[]> eldest) { return size() > MAX_ENTRIES; } }; public static byte[] get(String key) { synchronized (CACHE) { byte[] cached = CACHE.get(key); if (cached == null) { cached = load(key); CACHE.put(key, cached); } return cached; } } } 

The synchronized block is deliberately simple. It serializes cache access, which is fine for a low-QPS service but not for a high-throughput one. If contention matters, use a cache implementation with a documented maximum size and expiry policy rather than growing a home-made one. Also remember that an entry cap is only a memory cap when payloads are similar in size; if response bodies vary widely, cap total bytes or use a maximum-weight policy.

Other retaining references to check

The same workflow applies to two other patterns that show up in production.

ThreadLocal on a pooled thread. The ThreadLocal API documentation explains that each thread holds an implicit reference to its copy of a thread-local variable for as long as the thread is alive and the ThreadLocal instance remains reachable. A pool thread can therefore keep a request-scoped object alive long after the request ends. Always remove the value in a finally block:

try { REQUEST_CONTEXT.set(context); handle(context); } finally { REQUEST_CONTEXT.remove(); } 

Containers can help at undeploy time. Tomcat's ThreadLocal Leak Prevention Listener renews threads in executor pools when a context is stopped and configured to do so, but that only helps when a context stops; it does not clean up a long-running service whose pool threads never stop.

Listener and callback registries. A component that registers a listener on a long-lived object must remove it on shutdown. If the registry holds strong references, every registration keeps the listener's entire object graph alive. Prefer symmetric register/unregister methods, and verify removal in a test rather than relying on shutdown hooks.

Rerun the same measurement

A fix is a hypothesis until the same measurement comes back clean.

  1. Deploy the change to a canary with the same heap flags and the same GC logging.
  2. Replay the same load profile for at least as long as the original observation window.
  3. Compare the post-full-GC floor, not the peak. It should be flat, with enough headroom for traffic spikes.
  4. Take a second histogram at the same point in the cycle and confirm that the byte[] count stabilizes instead of climbing.
  5. Optionally take a second heap dump after the soak and check the cache's retained size in the dominator tree. It should stay near the configured cap multiplied by the average body size.

If the floor still climbs, return to Step 1. A second retaining reference is common: fixing the cache can expose a listener or ThreadLocal that was previously hidden under the larger leak. Treat the verification loop as part of the diagnosis, not as an afterthought.

Presenting the Investigation in an Interview

This kind of incident makes a strong interview story because it has a beginning, middle, and end: a symptom, a hypothesis, evidence, a root cause, a fix, and a measurement that proves the fix. Describe the slope of the post-collection floor before and after, name the retaining reference, and explain why the fix had to change the retention policy rather than swap in a different map implementation.

If you are preparing for interviews, connect the forensic steps to the mechanics behind them. This guide to Java memory management and garbage collection interview questions covers the broader set of GC and heap topics that experienced developers are expected to explain, which helps you move from "I ran MAT" to "here is why the collector could not reclaim the objects."

Conclusion

  • Confirm retention from the post-full-GC floor, not from the heap sawtooth; a flat high floor points to sizing, while a climbing floor under steady load points to a leak.
  • Capture a live-only dump with jcmd GC.heap_dump, budget for the pause and disk space, and keep the file restricted.
  • Use Leak Suspects to find the candidate, the Dominator Tree to measure retained memory, and Path to GC Roots to prove the retaining chain.
  • Fix the policy that never releases objects, whether that is an unbounded static map, a ThreadLocal without remove(), or an asymmetric listener registry.
  • Rerun the same load and the same GC measurement; the fix is proven when the floor is flat and the retained size stays bounded.