Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection

 
Pujan Shah
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch
This question has been discussed more than once, here is one post: objects eligible for GC

hth
 
Henry Wong
author
Marshal
Pie
Posts: 20999
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Pujan Shah
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry & Ahmed. I got it now.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic