class CardBoard {
Short story = 200;
CardBoard go(CardBoard cb) {
cb = null;
return cb;
}
public static void main(String[] args) {
CardBoard c1 = new CardBoard();
CardBoard c2 = new CardBoard();
CardBoard c3 = c1.go(c2);
System.out.println("c3 value : "+c3);
c1 = null;
System.out.println("c1 value : "+c1);
System.out.println("c2 value : "+c2);
// do Stuff
}
}
This is an example from the SCJP6 mock exam. The question states: When // doStuff is reached, how many objects are eligible for GC? And the answer is (2 objects) because: Only one CardBoard object (c1) is eligible, but it has an associated Short
wrapper object that is also eligible.
When I execute the code, it looks like c3 also points to null… so I would have said that 3 objects are eligible for GC.
Can someone please guide me through the logic of this code.
The object
c3is originally null, so there is no question of recollecting it, for it never existed in the first place. The garbage collector is meant to scavenge objects that actually exist on the heap.Among the rest, the reference to
c2is never discarded, and hence it will not be reclaimed. Although it appears that c2 is nullified in the statementCardBoard c3 = c1.go(c2);, this is not the case. The reference toc2has been passed in by value and although the reference is nullified, there is an existing reference to the object in the main method. Hence it will not be reclaimed.This leaves us with
c1, that has been explicitly nullified and hence eligible for collection. However, c1 also contains a reference to theShortvariable story, which does not have any inbound references from any other object. This results in two objects being eligible for scavenging – one CardBoard object and the embedded Short object.