After line 11 executes, how many X2 objects are eligible for garbage collection (note the cyclic references)? class X2 { public X2 x; public static void main(String [] args) { X2 x2 = new X2(); // line 6 X2 x3 = new X2(); // line 7 x2.x = x3; x3.x = x2; x2 = new X2(); x3 = x2; // line 11 doComplexStuff(); } }
-
A0
-
B1
-
C2
-
D3
-
EDepends on doComplexStuff()
Answer
Correct Answer: 2
Explanation
Introduction / Context:Java's garbage collector can reclaim cycles, because it is based on reachability from GC roots. Two objects that reference each other but are not reachable from roots are still eligible for collection.
Given Data / Assumptions:
x2andx3initially reference two different objects (A and B).- A and B point to each other (forming a 2-node cycle).
- Later,
x2is assigned to a new object C, andx3is set to refer tox2(thus both locals now point to C).
Concept / Approach:After line 11, there are no live references from GC roots to A or B. Mutual references between A and B do not prevent collection.
Step-by-Step Solution:
Before line 9: A and B exist and point to each other; both are referenced by locals.Line 10:x2 = new X2() creates C; local x2 points to C, but B still points to A and A to B.Line 11: x3 = x2 makes both locals point to C; neither A nor B is referenced from any root.Therefore, A and B are both eligible: count = 2.Verification / Alternative check:A mark-and-sweep collector marks only objects reachable from roots; A and B will not be marked and then will be swept.
Why Other Options Are Wrong:0 or 1 ignores that both A and B lost root reachability; 3 would require yet another unreferenced object.
Common Pitfalls:Mistaken belief that cycles are never collected (true for simple reference counting, but not for Java's tracing GC).
Final Answer:2