4.3 Object Lifecycle, Dereferencing & Garbage Collection
Key Takeaways
In a reference-graph exercise, track the new object, the paths that keep it reachable, and the point at which those paths are gone.
A cycle of references does not keep its objects reachable when no path from any live thread reaches the cycle.
Reference reassignment and null assignments change the reference graph. A Java implementation can identify an unused reference before the variable leaves lexical scope.
Calling System.gc() or Runtime.getRuntime().gc() is merely a hint to the JVM; garbage collection timing and execution are never guaranteed
The JVM calls
Object.finalize()at most once per object and gives no guarantee it will run before shutdown.
The Three Phases of an Object's Lifecycle
Unlike C or C++, Java provides no free or delete operator to destroy objects manually. Instead, the JVM's garbage collector (GC) automatically frees heap memory occupied by objects that the running program can no longer reach. Use three conceptual stages for ordinary object creation and reachability questions:
- Creation (Allocation & Initialization): Executing
new ClassName(...)allocates memory on the heap, zero-initializes fields, executes initializers and constructors, and yields a reference to the new object. - In Use (Reachable): As long as at least one live thread can follow a chain of strong references starting from a GC root (such as a live reference in an active method or a reachable class’s static field) to the object, the object is reachable and protected from collection.
- Eligible for Garbage Collection (Unreachable): Once every path from all GC roots to the object is broken, the object becomes unreachable—meaning it is eligible for garbage collection.
Important
Eligibility and collection timing are separate. The source-level examples assume the displayed variables’ references remain live until reassigned or out of scope. In actual execution, Java allows earlier collection eligibility for objects that the remaining computation cannot access. Collection may also be delayed.
Four Ways an Object Becomes Unreachable
At the Java source-code level, heap objects lose all live strong references in four classic ways:
1. Reassigning a Reference Variable
Pointing the sole reference variable to a different object leaves the first object orphaned:
StringBuilder sb = new StringBuilder("First"); // Obj1 created
sb = new StringBuilder("Second"); // Obj1 is now eligible for GC
2. Setting a Reference Variable to null
Explicitly clearing the sole reference severs the link immediately:
Object item = new Object(); // Obj1 created
item = null; // Obj1 is now eligible for GC
3. Reference Variable Going Out of Scope
As control leaves a block, the names of its locals are no longer in scope. A block need not have its own JVM frame. When following source-level references, check whether another variable or field still points to the object:
public void process() {
StringBuilder temp = new StringBuilder("Local"); // Obj1 reachable only via temp
} // Method returns: temp leaves scope, so Obj1 becomes eligible for GC
If a method returns the object and the caller keeps it, or stores it in a field reachable from a live thread, the reference survives the method. These are examples of a reference escaping its original scope.
4. Island of Isolation
Two or more objects can hold references to each other while having zero references from any live stack variable or static field. Java specifies reachability and leaves the collector implementation to the JVM. Circular links do not create a path from a live thread to the cluster:
public class Node {
Node partner;
public static void main(String[] args) {
Node n1 = new Node(); // NodeA
Node n2 = new Node(); // NodeB
n1.partner = n2; // NodeA points to NodeB
n2.partner = n1; // NodeB points to NodeA
n1 = null; // External path to NodeA broken (NodeB still points to NodeA)
n2 = null; // External path to NodeB broken -> Island of isolation!
// Both NodeA and NodeB are eligible for GC here
}
}
Notice that right after n1 = null;, NodeA is still reachable through n2.partner. Only after n2 = null; executes do both NodeA and NodeB form an unreachable island of isolation eligible for collection.
Tracing Multi-Line Dereference Puzzles
The most reliable way to solve multi-line exam puzzles is to label each created object (Obj1, Obj2, Obj3) and build a quick column-by-column trace table showing which object each variable points to after each line:
public class LifecyclePuzzle {
public static void main(String[] args) {
StringBuilder a = new StringBuilder("Alpha"); // Line 1: Obj1
StringBuilder b = new StringBuilder("Beta"); // Line 2: Obj2
StringBuilder c = a; // Line 3
a = b; // Line 4
b = null; // Line 5
c = new StringBuilder("Gamma"); // Line 6: Obj3
a = null; // Line 7
} // Line 8: method ends
}
| After Line | a points to | b points to | c points to | Objects Eligible for GC |
|---|---|---|---|---|
| Line 1 | Obj1 ("Alpha") | — | — | None |
| Line 2 | Obj1 | Obj2 ("Beta") | — | None |
| Line 3 | Obj1 | Obj2 | Obj1 | None |
| Line 4 | Obj2 | Obj2 | Obj1 | None (Obj1 held by c) |
| Line 5 | Obj2 | null | Obj1 | None (Obj2 held by a) |
| Line 6 | Obj2 | null | Obj3 ("Gamma") | Obj1 becomes eligible |
| Line 7 | null | null | Obj3 | Obj1, Obj2 becomes eligible |
| Line 8 | (out of scope) | (out of scope) | (out of scope) | Obj1, Obj2, Obj3 becomes eligible |
Tip
Track each object separately. In String copy = new String("Java");, the copy is a distinct object from the interned literal. Clearing the sole live reference to the copy changes its reachability. It does not give a collection deadline for the canonical string.
Why GC Timing Is Never Guaranteed (System.gc() & finalize())
Exam questions frequently try to trick you into predicting when garbage collection runs or how many times finalize() prints:
System.gc()andRuntime.getRuntime().gc(): Both methods only suggest that the JVM run garbage collection. The JVM may run GC immediately, run it later, or ignore the request completely.protected void finalize(): Defined onjava.lang.Object,finalize()may be invoked by the garbage collector 0 or 1 times—never twice on the same object, and never guaranteed to execute at all (for example, if the program exits before GC runs).
public class FinalizeTrap {
static FinalizeTrap keeper;
@Override
protected void finalize() throws Throwable {
System.out.println("finalize executed");
keeper = this; // Self-resurrection makes the object reachable again
}
public static void main(String[] args) {
FinalizeTrap item = new FinalizeTrap();
item = null;
System.gc(); // Hint only: output may be empty or print "finalize executed" once
}
}
Even if finalize() runs once and rescues the object by assigning this to keeper, and keeper is later set back to null, the JVM will not automatically invoke finalize() again for that object. An ordinary Java method call to a visible finalize method is a separate matter.
Examine the method below. Treat local references as live until reassigned or out of scope and track the four builders only. Immediately after // Line 6 executes, how many StringBuilder objects created in work are eligible for garbage collection?
public static StringBuilder work() {
StringBuilder s1 = new StringBuilder("One"); // Line 1
StringBuilder s2 = new StringBuilder("Two"); // Line 2
StringBuilder s3 = new StringBuilder("Three"); // Line 3
s1 = s3; // Line 4
s3 = null; // Line 5
s2 = new StringBuilder("Four"); // Line 6
return s1;
}
Zero objects
One object (only "One")
Three objects ("One", "Two", and "Three")
Two objects ("One" and "Two")
Consider the following Box class and main method:
public class Box {
Box next;
public static void main(String[] args) {
Box b1 = new Box();
Box b2 = new Box();
b1.next = b2;
b2.next = b1;
b1 = null;
// Point X
b2 = null;
// Point Y
}
}
Treat local references as live until reassigned or out of scope. Which statement accurately describes garbage-collection eligibility at Point X and Point Y?
Both Box objects are eligible at Point X because b1 was set to null
Zero Box objects are eligible at Point X; both Box objects are eligible at Point Y
Neither Box object is eligible at Point Y because b1.next and b2.next still reference each other
One Box object is eligible at Point X and two are eligible at Point Y
Which statement about System.gc() and Object.finalize() in Java SE 8 is TRUE?
Calling System.gc() forces the JVM to run garbage collection before the next statement executes
If an object resurrects itself during finalize() and later becomes unreachable again, the JVM runs finalize() a second time
The JVM invokes finalize() automatically at most once per object, and it may never run
Setting a local String variable initialized with the literal "Java" to null guarantees the "Java" literal is immediately destroyed
Sections you finish are checked off in the contents.