Card 08/ 09
All 9 cards
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.
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 — a whole island goes at once |
d | Yes | A 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.