Card 04/ 09

ExampleDifficulty: Intermediate1 min

Reachability Example: An Object Nothing Can Reach

Four lines, and after the third one of the two objects is already garbage.

An object becomes eligible for collection the moment the last reference to it moves elsewhere. Two builders, and one assignment:

java
StringBuilder first = new StringBuilder("one");
StringBuilder second = new StringBuilder("two");

first = second;

System.out.println(first);
text
two

Line 4 pointed first at the second builder. Nothing else was holding the first one, so after that line there is no chain of references to it from any variable the program is using (a root), and the garbage collector, the part of the JVM that frees unreachable objects, may take it whenever it next looks.

What each variable reaches after line 4
Afterfirst reachessecond reachesUnreachable
Line 2The "one" builderThe "two" builderNothing
Line 4The "two" builderThe "two" builderThe "one" builder

Setting first = null would have had the same effect on the "one" builder. Either way, what made it garbage was losing its last reference, not anything done to the object itself.

Nothing was deleted, and no method was called to release anything. The object became garbage because the last reference moved, which is the only way anything ever becomes garbage.