Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which objects are eligible for GC?

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.

like image 723
chronical Avatar asked Dec 13 '22 19:12

chronical


2 Answers

The object c3 is 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 c2 is never discarded, and hence it will not be reclaimed. Although it appears that c2 is nullified in the statement CardBoard c3 = c1.go(c2);, this is not the case. The reference to c2 has 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 the Short variable 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.

like image 92
Vineet Reynolds Avatar answered Dec 21 '22 22:12

Vineet Reynolds


CardBoard c1 = new CardBoard();

Creates a CardBoard instance and its Short instance. (2 objects) Assigns the CardBoard reference to c1.

CardBoard c2 = new CardBoard();

Creates another CardBoard instance and its Short instance. (2 more objects) Assigns the CardBoard reference to c2.

CardBoard c3 = c1.go(c2);

Assigns null to c3. (The go method is a trick to see if you understand Java argument passing semantics. If you think that Java uses pass-by-reference, you might incorrectly conclude that c2 is set to null by this call. In fact, c2 is unchanged.)

c1 = null;

Assigns null to c1. This renders the first CardBoard instance and its Short instance unreachable, and candidates for garbage collection.

The second CardBoard instance and its Short instance are still reachable.

like image 24
Stephen C Avatar answered Dec 22 '22 00:12

Stephen C