library
advancedGarbage Collection Roots & Memory Leaks
Identify GC roots, understand why objects aren't collected, and diagnose common Java memory leaks.
Garbage collection starts from GC roots — objects that are always reachable. Everything reachable from a root is alive; everything else is garbage.
GC roots = anchor points in a web. Any object connected to an anchor (directly or through a chain) survives. Memory leak = accidentally tying a string (reference) from an anchor to an object you meant to discard.
Key Concepts
1
GC Roots:
1. Local variables (stack frames of active threads)
2. Active threads themselves
3. Static fields of loaded classes
4. JNI references (native code)
5. Synchronization monitors (locked objects)
2
Common memory leaks in Java:
3
1. Static collections that grow forever:
static Map<String, Object> cache = new HashMap<>(); // never cleared
4
2. ThreadLocal not removed in thread pools:
Thread is reused → ThreadLocal value persists → leak
5
3. Listeners/callbacks not unregistered:
subject.addListener(this); // never removed
6
4. Inner classes holding outer reference:
Non-static inner class holds implicit reference to enclosing object
7
5. Unclosed resources:
Streams, connections, cursors holding native memory
8
6. String.intern() with unique strings:
Every interned string stays in the pool
9
Diagnosis tools:
- jmap -dump: capture heap dump
- jvisualvm / Eclipse MAT: analyze heap dumps
- -XX:+HeapDumpOnOutOfMemoryError: auto-dump on OOM
- jstat: monitor GC activity in real-time