aspose file tools*
The moose likes Beginning Java and the fly likes Garbage Collection Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Garbage Collection Question" Watch "Garbage Collection Question" New topic
Author

Garbage Collection Question

Abhi Bhutani
Greenhorn

Joined: Aug 26, 2008
Posts: 8
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

Joined: Aug 06, 2008
Posts: 23
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
Sheriff

Joined: Sep 28, 2004
Posts: 18141
    
  39

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Abhi Bhutani
Greenhorn

Joined: Aug 26, 2008
Posts: 8
All clear now. Thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Garbage Collection Question
 
Similar Threads
Objects - GC
Question from mock test
objects eligible for GC
Ques from Self Test in Chap3/K&B 5 ,page 266
Garbage Collection