GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage Collection Doubt 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 Doubt" Watch "Garbage Collection Doubt" New topic
Author

Garbage Collection Doubt

Srividhya Kiran
Ranch Hand

Joined: Feb 17, 2008
Posts: 166
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

Joined: Jan 16, 2008
Posts: 162
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

Joined: Jun 08, 2007
Posts: 7
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 ]
 
GeeCON Prague 2014
 
subject: Garbage Collection Doubt