In Java, the garbage collector frees the objects that nothing references anymore. So a memory leak is an object that is no longer useful but still referenced: the GC cannot free it. Oracle’s guide puts it this way: the application keeps references to objects “unintentionally”.
Here are six classic leaks, each one reproduced by a small program of the public repository java-gc-lab, with what you see and the fix.
What keeps an object alive The chain of references of a leak: a GC root, the static field AUDIT of the class StaticCollection, refers to an ArrayList, which refers to Order objects; they stay alive. A short-lived object that nothing refers to anymore is freed by the GC. What keeps an object alive every object reachable from a root stays alive GC root static AUDIT ArrayList the list of the field Order Order Order Order objects useless, but reachable stay alive: the leak short-lived object no reference left → freed by the GC The GC starts from “roots”: the static fields of the loaded classes, the local variables of the running threads… Every object that can be reached from a root stays alive. A leak is a path that someone forgot to cut.
...