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 }
-
Aafter line 5
-
Bafter line 6
-
Cafter line 7
-
DThere is no way to be absolutely certain.
-
Eimmediately after a.s(b) returns
Answer
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:
aandbare created;a.s(b)is invoked.- We do not know what
sdoes (it could storebinaor elsewhere). - Later,
bis set to null andais 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 createsb. 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.