This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt on garbage collection

 
Charu Murali
Ranch Hand
Posts: 37
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came acroos the following qn in a mock exam.
At what stage in the following method does the object initially referenced by s becomes available for garbage collection. Select the one correct answer.

void method X() {
String r = new String("abc");
String s = new String("abc");
r = r+1; //1
r = null; //2
s = s + r; //3
} //4


1.Before statement labeled 1
2.Before statement labeled 2
3.Before statement labeled 3
4.Before statement labeled 4
5.Never.
the ans they have given is 4. But I think garbage collection can not be forced or determined. Can anyone please clarify me.
Thanks
Charu
 
sean cee
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
True, GC cannot be forced or determined.
But the wording of the question is
"when does it become ELIGIBLE for GC ?"
That means
"IF GC start to kick in, will it be a candidate for GC or not?"
and an object becomes candidate for GC only if there is no reference to it..
so the answer given is correct.
Thanks
Sean
 
swarna kumar
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi sean,
we can not force the GC, but if we can set the obj.ref variable to null, hinting the GC to garbage collect the objects referred by the variables.
so from this programm,how can we say the ans is 4,
could u pls correct me,
swarna
 
Corey McGlone
Ranch Hand
Posts: 3271
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question does not ask when the object initially referenced by s will be garbage collection, it asks, only, when will it be eligible for garbage collection. This is roughly synonymous to asking at what point are there no references to the object from an active part of the application. Let me rephrase the question like this to see if it makes more sense: "At what point, if the garbage collection process were to execute, would the object originally referenced by s be garbage collected?"
Therefore, 4 is the correct answer because, after the last line of code in that block is executed, there are no references to the object in question. There is no guarantee when, or even if, the object will be garbage collected. It is, however, eligible for garbage collection, which is what the question asks.
I hope that helps,
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic