Card 08/ 09

ExerciseDifficulty: Advanced1 min

Four Objects: Which Are Eligible for Collection

At the marked line, decide for each of the four objects whether anything can still reach it. Write all four down before opening the reveal.

java
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?
Each object, whether it is reachable, and by what
ObjectReachable?Why
aYesHeld by a static list, which is a collection root
bNoIts only reference was set to null
cNoThe list holding it is itself unreachable — a whole island goes at once
dYesA live local variable in the current frame still points at it

c is the one worth pausing on. It still has a reference pointing at it — 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.