Sub topic 9
Memory leaks in a garbage-collected language
This chapter assumes you know the heap, GC roots and reachability from earlier chapters. You should also be comfortable with Java collections and running java from the command line.
What a leak means in Java
Java frees objects automatically, but it can only free objects that are unreachable. A memory leak in Java is an object the program will never use again but that is still reachable from a GC root. The collector cannot know your intent. It sees a chain of strong references and keeps everything on that chain.
This differs from a leak in C, where memory is lost because nobody holds a pointer to it. In Java the opposite happens: someone holds a reference for too long.
Recognizing the symptoms
A healthy heap shows a sawtooth pattern. Usage climbs as objects are allocated, then drops after each collection, and the low points stay roughly level. A leak shows up as a rising floor: the low point after each full collection is higher than the last.
Typical signs:
- Old generation occupancy grows steadily and never returns to its earlier level.
- Full GCs become more frequent, and each one frees less memory.
- GC pauses lengthen, and the application spends more time collecting than working.
- Eventually the JVM throws
OutOfMemoryError: Java heap space, orGC overhead limit exceededwhen the collector spends nearly all its time reclaiming almost nothing.
Slow growth is not proof of a leak. A cache that is still filling, or a heap that has not yet reached its steady state, looks similar. Judge by the post-full-GC floor over a long enough period, not by a single reading.
The simplest leak: a static collection that only grows
The following program from the chapter plan keeps every allocation reachable through a static field.
import java.util.ArrayList;
import java.util.List;
public class LeakDemo {
private static final List<byte[]> CACHE = new ArrayList<>();
public static void main(String[] args) {
while (true) {
CACHE.add(new byte[1024 * 1024]); // 1 MB kept reachable from a static field
}
}
}Static fields live as long as their class is loaded, and a class normally lives as long as the application. So CACHE is effectively a GC root. Run it with a small heap to see the failure quickly:
java -Xmx64m LeakDemoThe program ends with java.lang.OutOfMemoryError: Java heap space. Real leaks are rarely this obvious, because the growth happens inside a map, a listener list or a framework object rather than in a loop.
Common causes in real programs
Unbounded caches and registries
A HashMap used as a cache with no eviction policy grows with the number of distinct keys. If keys come from user input, such as session IDs, request parameters or file names, growth has no upper limit. The same applies to maps that record "seen" items, metrics keyed by dynamic labels, and registries that add entries but never remove them.
Listeners and callbacks that are never removed
When you register an object with a long-lived publisher, the publisher holds a strong reference to it. If the subscriber is short-lived, such as a UI panel or a request handler, it stays reachable until you deregister it. Everything the subscriber references stays alive too.
import java.util.ArrayList;
import java.util.List;
public class EventBus {
private final List<Runnable> listeners = new ArrayList<>();
public void subscribe(Runnable listener) {
listeners.add(listener);
}
public void unsubscribe(Runnable listener) {
listeners.remove(listener);
}
public void publish() {
for (Runnable l : new ArrayList<>(listeners)) {
l.run();
}
}
}Always pair subscribe with unsubscribe, for example in a close() method or a finally block. The loop above copies the list before iterating so a listener can unsubscribe safely during delivery.
Keys without `equals` and `hashCode`
If a class used as a map key does not override equals and hashCode, two logically equal keys are different to the map. Each lookup misses and each insert adds a new entry.
import java.util.HashMap;
import java.util.Map;
public class BadKeyDemo {
static class Key {
final int id;
Key(int id) { this.id = id; }
// equals and hashCode are not overridden
}
public static void main(String[] args) {
Map<Key, String> map = new HashMap<>();
for (int i = 0; i < 1_000_000; i++) {
map.put(new Key(42), "value"); // same logical key every time
}
System.out.println("Entries: " + map.size()); // prints 1000000, not 1
}
}A related bug is mutating a key after inserting it. The entry's hash no longer matches its bucket, so you cannot find or remove it, yet the map still holds it.
ThreadLocal values in thread pools
A ThreadLocal stores a value in a map owned by each thread. In a pool, threads live for the whole application, so values you set and never remove live just as long. This is worse when the value references a class loaded by a web application's class loader, because it can pin the whole loader after a redeploy.
public class RequestContext {
private static final ThreadLocal<byte[]> BUFFER = new ThreadLocal<>();
public static void handle() {
BUFFER.set(new byte[1024 * 1024]);
try {
// use the buffer for this request
} finally {
BUFFER.remove(); // without this, the buffer stays with the pooled thread
}
}
}Inner classes and lambdas that capture `this`
A non-static inner class holds an implicit reference to its enclosing instance. A lambda that uses an instance field or method also captures this. If you hand such an object to a long-lived structure, you keep the entire outer object alive, even when you only meant to keep something small. Prefer a static nested class, or copy the needed values into locals before creating the lambda.
Resources outside the heap
Unclosed streams, sockets, database connections and ByteBuffer.allocateDirect buffers can exhaust native memory or file descriptors while the heap looks fine. Use try-with-resources for anything that implements AutoCloseable. This kind of failure shows up as OutOfMemoryError: Direct buffer memory, "Too many open files", or a growing process size that the heap does not explain.
Class loader leaks
Classes and their metadata live in Metaspace and are unloaded only when their class loader becomes unreachable. A static reference, a ThreadLocal or a running thread that points into a loader keeps all its classes alive. Repeated redeploys in an application server then cause OutOfMemoryError: Metaspace.
Fixing leaks by choosing the right lifetime
The remedy is to decide how long each reference should live and make the code enforce it.
| Situation | Fix |
|---|---|
| Cache with unbounded keys | Set a maximum size and an eviction policy, or use a caching library with expiry |
| Registry of short-lived objects | Provide explicit removal, or hold entries weakly |
| Listener lifetime shorter than publisher | Unsubscribe in `close()` or `finally` |
| Per-request state in pooled threads | Call `ThreadLocal.remove()` in `finally` |
| Map keys | Override `equals` and `hashCode`, and use immutable keys |
| Native resources | try-with-resources |
A bounded least-recently-used cache needs only LinkedHashMap:
import java.util.LinkedHashMap;
import java.util.Map;
public class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int maxEntries;
public LruCache(int maxEntries) {
super(16, 0.75f, true); // true = order by access
this.maxEntries = maxEntries;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxEntries;
}
public static void main(String[] args) {
LruCache<Integer, String> cache = new LruCache<>(3);
for (int i = 0; i < 10; i++) {
cache.put(i, "value" + i);
}
System.out.println(cache.keySet()); // [7, 8, 9]
}
}This class is not thread-safe. Wrap it with Collections.synchronizedMap or use a dedicated caching library when several threads share it.
Weak references: use with care
WeakHashMap holds its keys weakly, so an entry disappears once nothing else strongly references the key. This suits metadata attached to objects whose lifetime you do not control. It is a poor general-purpose cache: entries vanish at the next collection regardless of how useful they are. It also fails when the value strongly references its own key, because the value keeps the key reachable and the entry never goes away. For caches that should shrink under memory pressure, soft references fit better, but a bounded size is usually more predictable.
A practical investigation workflow
- Confirm the trend. Enable GC logging, for example
-Xlog:gc*:file=gc.log, and check whether the heap after each full GC keeps rising. - Narrow down the growing types. Run
jcmd <pid> GC.class_histogramtwice, a few minutes apart, and compare the instance counts. Types whose counts only increase are suspects. Common culprits arebyte[],String,HashMap$Nodeand your own domain classes. - Capture a heap dump, either on demand with
jcmd <pid> GC.heap_dump file.hprofor automatically with-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./dumps. - Open the dump in a heap analyzer such as Eclipse MAT or VisualVM. Look for the largest retained sizes, then follow the path to GC roots for a suspect object. That path shows exactly which static field, thread or collection holds the memory.
- Fix the retention, then repeat step 1 to confirm that the floor stays level.
Heap dumps of large heaps are big files and may contain sensitive data such as passwords and personal records. Store them securely and delete them when finished.
Edge cases to keep in mind
- A bounded cache can still hold too much if each entry is large. Limit by approximate size, not just entry count, when values vary widely.
- Leaks often hide in code you did not write: frameworks, drivers and logging libraries keep their own static registries. The path to GC roots in a heap dump reveals them.
- Not every high-memory program leaks. A heap that is simply too small for the working set also fails with
OutOfMemoryError, and the fix there is a larger-Xmxor less data, not a code change. - Finalizers and
Cleaneractions delay reclamation of the objects they guard. Avoid finalizers, and use try-with-resources for deterministic cleanup.
Exercise
A web service uses a fixed thread pool. Each request sets a 2 MB ThreadLocal<byte[]> buffer and never removes it. After the load spike ends, heap usage stays high even after full GCs. Why, and what is the fix?
Show answer
The pooled threads live for the whole application, and each thread's ThreadLocal map holds a strong reference to its buffer, so the buffers stay reachable from the thread, which is a GC root. A full GC cannot free them. The fix is to call BUFFER.remove() in a finally block at the end of each request, so the reference is dropped when the work is done.
Exercise
You compare two jcmd <pid> GC.class_histogram outputs taken ten minutes apart. The count of byte[] instances is unchanged, but com.example.Session instances rose from 40,000 to 90,000 while the active user count stayed constant. What does this suggest, and what is the next step?
Show answer
It suggests sessions are being retained after they should have ended, for example in a static map or listener list that is never cleaned up. The next step is to capture a heap dump and, in a heap analyzer, follow the path to GC roots from a Session instance to find the field or collection that holds it. Then add removal or an eviction bound there.