When an object becomes unreachable¶
โ Java 17 ยท Destroying Objects and Memory Management ยท 1/2
Objects on the heap, references in variables¶
Every object created with new lives on the heap, a memory area managed by the JVM. A variable only holds a reference to it:
Two objects on the heap, two references pointing at them.
In C or C++, you would free each object yourself. In Java, the JVM frees an object once nothing can reach it anymore. Such an object is eligible for garbage collection.
Way 1 โ The reference changes¶
Reassigning a reference, or setting it to null, can leave an object with no reference at all:
Movie m = new Movie("Dune");
m = new Movie("Avatar"); // "Dune" has no reference left โ eligible
m = null; // "Avatar" has no reference left โ eligible
Note the first case: m was never set to null, yet "Dune" became unreachable. Pointing a reference at another object is enough.
Way 2 โ The reference goes out of scope¶
A local variable disappears at the end of its block. If it was the only reference to an object, that object becomes unreachable:
void loadContent() {
Episode ep = new Episode("S01E01");
// ep is in scope: the Episode is reachable
} // ep goes out of scope
// after the method returns, the Episode has no reference โ eligible
When a method ends, all its local variables go out of scope at once.
Several references keep an object alive¶
An object stays reachable as long as at least one reference points to it:
Series s1 = new Series("Stranger Things");
Series s2 = s1;
s1 = null; // s2 still points to it โ NOT eligible
What counts isn't one variable, but whether any part of the program can still reach the object. That includes references stored inside other objects: an object kept in a field of a reachable object is still reachable.
Becoming eligible doesn't mean being deleted right away. That's the collector's call.