Java has a garbage collector. How can a Java program still have a memory leak?
Options
- It cannot, because the GC always frees every object
- By keeping references to objects it no longer needs (Correct option)
- Only by calling
System.gc()too many times in a row - Only by using primitives instead of objects everywhere
Answer
By keeping references to objects that are no longer needed, e.g. a static map/cache that only grows, forgotten listeners, or unclosed ThreadLocals
Why
The GC frees objects that nothing can reach anymore. A leak in Java means objects are still reachable (something still points to them) but your program will never use them again.
Typical causes: a static Map used as a cache with no size limit or expiry; listeners or callbacks registered and never removed; ThreadLocal values in pooled threads; unclosed resources.
Symptoms: heap grows until OutOfMemoryError. Tools: heap dump + Eclipse MAT, VisualVM, JFR.
Remember
Leak = still reachable but never used again.