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.s
does (it could store b
in a
or elsewhere).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:
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.
Discussion & Comments