Card 08/ 09
Practice: Which Objects Are Eligible for Collection
Four objects, a static list, a null and a discarded list: which can still be reached.
An object is eligible for garbage collection, the JVM freeing its memory, once nothing reaches it. It survives while a path from a root, such as a live local variable or a static field, still reaches it. At the marked line in the method below, decide for each of the four objects whether anything can still reach it, all four before opening the answer.
class Holder { static List<Object> kept = new ArrayList<>(); }
void run() {
Object a = new Object();
Object b = new Object();
Object c = new Object();
Object d = new Object();
Holder.kept.add(a);
b = null;
List<Object> local = new ArrayList<>();
local.add(c);
local = null;
// here
}Which of the four can still be reached at the marked line?
| Object | Reachable? | Why |
|---|---|---|
a | Yes | Held by a static list, which is a collection root |
b | No | Its only reference was set to null |
c | No | The list holding it is itself unreachable, and a whole island goes at once |
d | Yes | A live local variable in the current frame still points at it |
c is the one to look at closely. It still has a reference pointing at it, since the list holds one, and that reference is on an object nothing can reach. Reachability is about paths from roots, so an island of objects all pointing at each other is collected whole.
a is the shape every leak has. It was added to something long-lived and nothing will ever remove it, so it will outlive the method, the request and probably the day.
← → move through sections and cards