Memory leaks in Java
A Java memory leak is an object you no longer need that is still reachable, so the collector cannot free it. The heap grows until the process dies or a cache evicts.
Detailed Explanation
There is no forgotten free. There is forgotten reachability. A static Map that grows with every request, a listener you registered and never removed, a ThreadLocal on a pool thread, an inner class that pins its outer instance in a cache, a HashMap that uses a custom key whose equals is broken so entries never match for removal — all of these look like leaks.
The heap dump tells the story. You find a few objects that retain a large retained-size subgraph. jcmd GC.heap_dump, Eclipse MAT, or VisualVM. Look at incoming references, not only the type of the big array.
Caches without bounds are the most common production leak. computeIfAbsent on a ConcurrentHashMap keyed by every user id is a map of the entire user table. Use a size limit and a TTL. Soft references delay the problem; they do not cap it.
Classloader leaks are a second family: a static cache in a class loaded by a webapp classloader, referenced from a parent thread pool, keeps the whole app alive after "undeploy". Remove shutdown hooks and clear thread locals on undeploy.
You reach for leak analysis when old gen grows across GCs (the live set rises), not when allocation rate is high. High allocation with a flat live set is healthy churn.
The cost of a leak is OutOfMemoryError or a container OOM kill. The cost of a dump on a huge heap is a pause and a large file. Take dumps with a plan. The cost of "fixing" a leak by raising -Xmx is a larger corpse.
Prevention: no unbounded static collections, remove on thread locals, weak listeners or explicit unregister, bounded caches, no inner classes stored globally.
Code Examples
import java.util.HashMap;
import java.util.Map;
public class Unbounded {
private static final Map<String, byte[]> CACHE = new HashMap<>();
static void leak(String id) {
CACHE.put(id, new byte[1024]); // never removed: a leak if id is unbounded
}
public static void main(String[] args) {
leak("a");
System.out.println(CACHE.size()); // prints: 1
}
}public class Listener {
interface Tick { void onTick(); }
static final java.util.List<Tick> TICKS = new java.util.ArrayList<>();
static void register(Tick t) {
TICKS.add(t);
}
static void unregister(Tick t) {
TICKS.remove(t); // forgetting this leaks t and everything it closes over
}
public static void main(String[] args) {
Tick t = () -> {};
register(t);
unregister(t);
System.out.println(TICKS.size()); // prints: 0
}
}Common Gotchas
High allocation is not a leak
a rising live set after full GC is.
Inner instances stored in a static cache pin the outer object
Inner instances stored in a static cache pin the outer object
Raising `-Xmx` hides a leak until the new ceiling
Raising `-Xmx` hides a leak until the new ceiling