Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection Doubt

 
Srividhya Kiran
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello

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
} }

why in this code only 2 objects that is c1 and Short object associated with c1 are eligible for GC.

after the call to go c3 also becomes null right? and in go() we are setting cb also to null so even thats eligible right??

can someone explain to me this code??

This code is from K & B test pg:266

Thanks

Srividhya
 
sridhar row
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
} }

In the above code 2 objects are eligible for GC. But the 2 objects are c1 and c3 not sure how Short wrapper object is eligible or how it is associated with c1. I think c2 is not eligible because that reference is a local copy that is set to null.
[ March 27, 2008: Message edited by: sridhar row ]
 
Praful Asher
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lemme see,

c1 refers to a new Cardboard instance...(CardBoard c1 = new CardBoard() ; )
c2 refers to a new Cardboard instance...(CardBoard c2 = new CardBoard() ; )

c1.go(c2) sends a copy of the reference variable c2 to the go() method...not c2 itself...so even if cb is set to null, c2 still is unchanged...hence a valid reference and hence the concerned object is not eligible for GC.

Poor ol' c3 never actually got to refer any object as c1.go(c2) returned null.

So, in theory, the only object that gets eligible for GC is c1 (because of c1=null ; )

Also, any other object references that c1 contains also become eligible for GC...so the short object within c1 is done for as well... (No clue as to whether Wrappers are pooled...since they are immutable as well...someone might want to pitch in there...).

Regards,
Praful.
[ March 27, 2008: Message edited by: Praful Asher ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic