aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Garbage Collection" Watch "Garbage Collection" New topic
Author

Garbage Collection

Pujan Shah
Greenhorn

Joined: Jun 28, 2007
Posts: 4
Following example is from K&B book chapter 3. It is part of self test example. Can someone explain why there are 2 objects (c1=null and Short story=5 ) eligible for GC?

As i do see there should be 4 variables eligible for gc because at line c3= c1.go(c2); means c3 =null after execution and same time c2/cb also becomes null in same process.

so eventually c1,short,c2 and c3 should be eligible for gc. no?

Thanks!


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
} }
When // doStuff is reached, how many objects are eligible for GC?
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
Welcome to JavaRanch
This question has been discussed more than once, here is one post: objects eligible for GC

hth
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18848
    
  40

As i do see there should be 4 variables eligible for gc because at line c3= c1.go(c2); means c3 =null after execution and same time c2/cb also becomes null in same process.

so eventually c1,short,c2 and c3 should be eligible for gc. no?


Variables are *not* eligible for GC -- objects are eligible for GC. And setting a variable to null doesn't make an object eligible for GC. It just removes one of the references to an object. An object is eligible only when it is no longer reachable.

Anyway...

c1=null does make an object no longer reachable.

c3=null doesn't do anything. It was null before the method call. There was nothing to make not reachable.

cb=null does eliminate a reference to the object referred to by c2, but c2 is still referring to the object. Setting cb=null doesn't make c2=null. Hence, it is still reachable.

There is actually 2 Short references. But since autoboxing a value of 5 was used, they are referring to the same object. This object could never be eligible for GC, because a reference of it, is available in the cache.


So... only one object is eligible for GC.

Henry


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

Joined: Jun 28, 2007
Posts: 4
Thanks Henry & Ahmed. I got it now.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Garbage Collection