Memory Leaks: Finding the Culprit

Memory Leaks: Finding the Culprit in Java: Java has a garbage collector, so it cannot leak memory — a claim that is technically true and practically false.

Concept Explanation

Java has a garbage collector, so it cannot leak memory — a claim that is technically true and practically false. The GC only frees objects that are unreachable. An object you forgot about but that is still referenced is a leak in every meaningful sense.

The symptom: memory rises steadily, GC runs more and more often, and eventually OutOfMemoryError: Java heap space.


The Classic Leaks

1. A growing static collection

public class Cache {
    private static final Map<String, byte[]> CACHE = new HashMap<>();

    public static void put(String k, byte[] v) {
        CACHE.put(k, v);        // nothing ever removes anything
    }
}

Static means "lives as long as the JVM". Without eviction this grows forever. Use a bounded cache (Caffeine, Guava) with a size or time limit.

2. Unclosed resources

// LEAK — the stream is never closed if an exception is thrown
InputStream in = new FileInputStream(path);
process(in);
in.close();
// Closed on every path, including exceptions
try (InputStream in = new FileInputStream(path)) {
    process(in);
}

3. Listeners that are never removed

publisher.subscribe(this);     // registered
// ...but never unsubscribed, so the publisher holds `this` forever

4. Inner classes holding their outer instance A non-static inner class keeps an implicit reference to the enclosing object. If the inner instance outlives it — sitting in a thread pool, say — the outer object cannot be collected. Mark it static when it does not need the outer instance.

5. ThreadLocal in a pooled thread

private static final ThreadLocal<HeavyContext> CTX = new ThreadLocal<>();

void handle() {
    CTX.set(new HeavyContext());
    try { doWork(); }
    finally { CTX.remove(); }        // essential — threads are reused
}

Without remove(), the value survives in the pooled thread for the life of the application.


Finding One

Reproduce it, then measure:

# Watch GC behaviour in real time
jstat -gc <pid> 1000

# Capture a heap dump on failure
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/dump.hprof MyApp

# Or on demand
jmap -dump:live,format=b,file=heap.hprof <pid>

Open the dump in Eclipse MAT or VisualVM and look for:

  • Which class holds the most bytes.
  • The dominator tree — what keeps those objects alive.
  • Instance counts growing between two dumps taken minutes apart.

Two dumps compared is far more informative than one, because it shows what is growing rather than what is merely big.


The Rising Sawtooth

Healthy memory usage looks like a sawtooth: rise, GC, drop to roughly the same baseline. A leak looks like a sawtooth whose troughs keep climbing — each GC recovers less than the last.


Common Mistakes

  1. Calling System.gc() to "fix" it: It does not help. The objects are reachable; that is the problem.
  2. Raising -Xmx and calling it done: Buys time, and delays the crash to a worse moment.
  3. Guessing from code review alone: Take a heap dump. The answer is usually surprising.
  4. Unbounded caches: The most frequent cause in real applications.
  5. Ignoring OutOfMemoryError: Metaspace: A different problem — usually classloader leaks from repeated redeployment.

Best Practices

  • Bound every cache by size, by time, or both.
  • try-with-resources for anything closeable, without exception.
  • Always remove() a ThreadLocal in a finally block.
  • Enable -XX:+HeapDumpOnOutOfMemoryError in production — you get one chance to capture the evidence.
  • Alert on the GC trough trend, not just peak memory.

Practice Exercises

  1. The Deliberate Leak: Write a static list that accumulates large arrays, run with -Xmx64m, and capture the resulting heap dump.
  2. The Dump Analysis: Open that dump in VisualVM or MAT and identify the dominator holding the memory.
  3. The ThreadLocal Fix: Set a ThreadLocal in a fixed thread pool task without removing it, confirm the value persists into the next task, then fix it.