Java reachability: When is the B object (created on line 3) definitely eligible for garbage collection? void start() { A a = new A(); B b = new B(); // line 3 a.s(b); b = null; // line 5 a = null; // line 6 System.out.println("start completed"); // line 7 }

Difficulty: Medium

Correct Answer: There is no way to be absolutely certain.

Explanation:


Introduction / Context:
Garbage-collection questions often hinge on whether other references exist. If a method stores a passed object, that object can remain reachable even after local variables are nulled out. Here, the behavior of a.s(b) is unknown.



Given Data / Assumptions:

  • a and b are created; a.s(b) is invoked.
  • We do not know what s does (it could store b in a or elsewhere).
  • Later, b is set to null and a is set to null.


Concept / Approach:
An object is eligible for GC only when it becomes unreachable from all GC roots. If method s stores b in a field of a (or some static/global structure), b may remain reachable beyond line 6. Without the method's contract, you cannot assert eligibility at a fixed line.



Step-by-Step Reasoning:

Line 3 creates b. It is definitely reachable via local b.Line 4 (a.s(b)) may create additional references to b.Line 5 drops local reference b, but other references may exist.Line 6 drops local reference to a, which might still be reachable elsewhere.


Verification / Alternative check:
Only with details of s (e.g., source code) can we track references precisely. If s did nothing, b would become eligible after line 6; but that cannot be guaranteed here.



Why Other Options Are Wrong:
They assert a specific line without accounting for the unknown side effects of a.s(b).



Common Pitfalls:
Assuming that setting local variables to null immediately frees objects; ignoring potential aliasing created by method calls.



Final Answer:
There is no way to be absolutely certain.

More Questions from Garbage Collections

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion