Java Memory Leaks and How to Find Them
A memory leak in Java doesn’t mean lost memory — it means unintentional object retention. The GC can’t reclaim objects that are still reachable, even if your code is done with them.
What a Memory Leak Looks Like
Heap Usage Over Time:
^ Heap
│ ╱──╲ ╱───╲ ╱────╲
│ ╱─ ╲──╱ ╲───╱ ╲──── Normal (sawtooth)
│ ╱─
│ ╱
└──────────────────────────────────► Time
^ Heap
│ ╱──── OOM!
│ ╱───╱
│ ╱───╱
│ ╱───╱ Leak (baseline grows)
│ ╱───╱
│ ╱───╱
│╱───╱
└──────────────────────────────────► Time
Healthy: Sawtooth pattern — GC reclaims, heap drops back.
Leak: Baseline keeps rising after each GC — eventually OutOfMemoryError.
Common Causes
1. Static Collections
public class EventCache {
// ❌ Never cleaned — grows forever
private static final List<Event> events = new ArrayList<>();
public static void addEvent(Event event) {
events.add(event);
}
}
Fix: Use bounded collections, or remove old entries.
// ✅ Bounded cache
private static final Queue<Event> events = new LinkedBlockingQueue<>(1000);
// Or use Caffeine/Guava cache with eviction
2. Unclosed Resources
// ❌ Connection never closed on exception
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
// if exception here → connection leaked
Fix: Always use try-with-resources.
// ✅ Auto-closed
try (Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users")) {
// process results
}
3. Listener / Callback Accumulation
// ❌ Listeners added but never removed
public class EventBus {
private final List<EventListener> listeners = new ArrayList<>();
public void register(EventListener listener) {
listeners.add(listener);
}
// No unregister method → listeners accumulate
}
4. ThreadLocal Misuse
// ❌ In a thread pool, threads are reused — ThreadLocal values persist
private static final ThreadLocal<UserContext> context = new ThreadLocal<>();
public void handleRequest(Request req) {
context.set(new UserContext(req.getUser()));
process(req);
// Forgot context.remove() → leaks in thread pools
}
Fix: Always clean up in a finally block.
try {
context.set(new UserContext(req.getUser()));
process(req);
} finally {
context.remove(); // ✅ Always clean up
}
5. ClassLoader Leaks
Common in application servers during redeployment:
Redeploy #1: ClassLoader-A loads classes → holds static refs
Redeploy #2: ClassLoader-B created, ClassLoader-A should be GC'd
BUT: a ThreadLocal or static ref still points to ClassLoader-A
→ All classes from ClassLoader-A are retained
OutOfMemoryError Types
| Error | Cause | Typical Fix |
|---|---|---|
java.lang.OutOfMemoryError: Java heap space |
Heap full | Increase -Xmx, fix leak |
java.lang.OutOfMemoryError: Metaspace |
Too many classes loaded | Increase -XX:MaxMetaspaceSize, fix classloader leak |
java.lang.OutOfMemoryError: GC overhead limit exceeded |
>98% time in GC, <2% heap freed | Fix leak, increase heap |
java.lang.OutOfMemoryError: Direct buffer memory |
Too many NIO direct buffers | Increase -XX:MaxDirectMemorySize |
java.lang.OutOfMemoryError: unable to create native thread |
OS thread limit reached | Reduce thread count, increase ulimit |
Taking Heap Dumps
# Manual dump
jmap -dump:format=b,file=heap.hprof <PID>
# Auto-dump on OOM (ALWAYS enable this in production)
java -XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/var/dumps/ \
-jar app.jar
# With jcmd (preferred)
jcmd <PID> GC.heap_dump /tmp/heap.hprof
Analyzing with Eclipse MAT
- Download Eclipse MAT
- Open heap dump: File → Open Heap Dump →
heap.hprof - Run Leak Suspects Report (auto-detects likely leaks)
Key Views
| View | Shows |
|---|---|
| Leak Suspects | Auto-detected likely leaks with details |
| Dominator Tree | Objects retaining the most memory |
| Histogram | Object count and size by class |
| Path to GC Roots | Why an object isn’t garbage collected |
Walkthrough
1. Open dump → "Leak Suspects Report"
→ "Problem Suspect 1: 523MB retained by java.util.ArrayList"
2. Click → Dominator Tree
→ com.example.EventCache → ArrayList → 2,000,000 Event objects
3. Right-click → "Path to GC Roots" → "exclude weak references"
→ GC Root: static field EventCache.events → ArrayList → Event
4. Fix: The static list is never cleared!
Analyzing with VisualVM
# Comes with JDK or download separately
jvisualvm
# Or use jconsole
jconsole
- Connect to running JVM
- Monitor tab → watch heap usage trend
- Sampler → memory → see allocation hotspots
- Heap Dump → browse objects
Prevention Patterns
| Pattern | Implementation |
|---|---|
| Bounded caches | Caffeine cache with maximumSize and expireAfterWrite |
| Try-with-resources | All Closeable resources |
| Weak references | WeakHashMap for caches that can be GC’d |
| ThreadLocal cleanup | finally { threadLocal.remove(); } |
| Resource pools | HikariCP (connections), thread pools with bounds |
Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Not enabling -XX:+HeapDumpOnOutOfMemoryError |
Can’t debug OOM after the fact | Always enable in production |
Analyzing heap dumps with jhat |
Deprecated, slow, limited | Use Eclipse MAT |
| Ignoring growing heap baseline | Leak not caught until OOM | Monitor with alerts |
Using finalize() |
Delays GC, causes phantom leaks | Use Cleaner or try-with-resources |
Key Takeaways
- Java leaks = unintentional retention — objects reachable but not needed.
- Top causes: static collections, unclosed resources, ThreadLocal, listeners.
- Always enable
-XX:+HeapDumpOnOutOfMemoryErrorin production. - Eclipse MAT Leak Suspects report is the fastest way to find the root cause.
- Use bounded caches, try-with-resources, and weak references to prevent leaks.
What’s Next?
Next: Java Performance Profiling — finding CPU hotspots, allocation bottlenecks, and using JFR and flame graphs.