How do memory leaks happen in Java, and what are the most common causes?
A memory leak in Java happens when an object is still reachable when it should not be. The collector cannot free it, because something still points at it, and it stays in the heap for the whole life of the program.
There are three common causes, and they cover most of the leaks that people find in real programs.
The first one is a collection that only ever grows. A static list that things are added to and never removed from is the simplest example. The leak is not that the list is big, it is that the list keeps a reference to every object that was ever put in it.
The second one is a listener that is never removed. If an object registers itself as a listener on something that lives for ever, such as a static event bus, then the listener is kept alive for ever as well.
The third one is a cache that has no limit. A map that is used as a cache but is never cleared grows until it holds everything the program has ever seen.
import java.util.ArrayList;
import java.util.List;
public class Main {
// A static collection that only ever grows.
private static final List<String> LOG = new ArrayList<String>();
public static void main(String[] args) {
for (int index = 0; index < 100000; index++) {
LOG.add("the message number " + index);
}
Runtime runtime = Runtime.getRuntime();
long used = runtime.totalMemory() - runtime.freeMemory();
System.out.println("the used heap MB : " + (used / (1024 * 1024)));
System.out.println("the log holds : " + LOG.size() + " messages");
}
}
There are two more that are worth knowing about. A value in a thread local that is never removed keeps the object alive for as long as the thread lives, and that is a common leak in a server where the threads are long lived. And an inner class that is not static keeps a reference to the object that made it, so holding on to the inner class holds on to the outer object as well.
The next question in this topic looks at how to find one.