ProLesson 10.7Advanced3 min readUpdated 30 October 2026
Memory leaks and OutOfMemoryError
Yes, Java can leak memory. The common causes, the different OutOfMemoryError messages, and a step-by-step way to find a leak with heap dumps.
Garbage collection frees unreachable objects. A Java memory leak happens when objects you no longer need are still reachable, so the GC isn't allowed to free them. The heap slowly fills until the application slows down and crashes with OutOfMemoryError.
01The usual suspects
- Static collections that only grow: a
static Mapused as a cache with no limit or expiry. - Listeners and callbacks never removed: a registered listener keeps its object, and everything that object references, alive.
- ThreadLocal values in thread pools: pool threads live forever, so values set and never
remove()d live forever too. - Inner classes and lambdas that capture a large outer object and are stored somewhere long-lived.
- Unclosed resources: streams, connections and result sets, which also hold native memory.
- Bad
equals/hashCodeon map keys: equal keys don't match, so "updates" keep adding new entries. - Class loader leaks in app servers or hot reload, which fill metaspace.
Loading the rest of the lesson…