Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection Question

 
Abhi Bhutani
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the K&B SCJP study guide book there is a question related to garbage collection. I have a doubt or you can say i have a question regarding the textbook answer so i need an explanation.


class CardBoard {
Short story = 5;
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 );
c1 = null;
// do stuff
}
}

Question: When //doStuff is reached, how many objects are eligible for Garbage Collection ?
My answer is 3. The objects i think eleigible are c1, the Short object associated with c1 and c3.

But according to the book only 2 objects are eligible: c1 and the Short object associated with it.

So i need an explanation that 'Why is c3 not eligible for gc since it references a null object that it obtained from the method go'.

Thanks
Abhi
 
Mario Minutolo
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Abhi Bhutani:


So i need an explanation that 'Why is c3 not eligible for gc since it references a null object that it obtained from the method go'.


c3 is not eligible for garbage collection because it does not refer to any instance of an object.

c3 is just a reference to null, so nothing can be garbage collected.
[ August 26, 2008: Message edited by: Mario Minutolo ]
 
Henry Wong
author
Marshal
Pie
Posts: 21212
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, please check the errata for the K&B book. As written, the Short object also can't be GC'ed because it is autoboxed, and has a value which is cached.

In the new version, the Short reference is assigned a value of 200.

Henry
 
Abhi Bhutani
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All clear now. Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic