Video in progress
Since there is a garbage collector, can a Java application still have a memory leak?
Yes. The GC collects only unreachable objects. If an object is no longer needed but some static collection, cache or listener still holds a reference to it, it is never cleaned.
📖 Answer
A leak in Java is a "forgotten reference". For the GC the object is alive, because there is a path to it.
Typical examples:
- a static collection: adding to
static List<Request> historyand never removing; - an unbounded cache: keys keep going into a
HashMap, but there is no eviction; - listeners: subscribing to an event bus and never unsubscribing;
- ThreadLocal: a value not
remove()d on a thread in a thread pool stays as long as the thread lives; - a wrong
equals/hashCode: the key "disappears" in aHashMap, but stays inside.
The signs: on the heap graph, the minimum after each GC slowly rises, and in the end you get OutOfMemoryError.
How to find it: take heap dumps at two points in time and see in Eclipse MAT which object counts grew and who is holding them (path to GC roots).
If you need a cache, don't write your own; take a library with size and TTL limits, like Caffeine.
Sign up to mark studied questions and save your progress.