Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage collection

 
Mathangi Shankar
Ranch Hand
Posts: 56
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

At what stage in the following method does the object initially referenced by s becomes available for garbage collection.

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

The answer for this question is that theobject labelled 'obj'is garbage collected Before statement labeled 4.

Please anyone explain me the solution of the above code.

Mathangi....
 
Abdulla Mamuwala
Ranch Hand
Posts: 225
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shankar

A object is garbage collected when all live threads loose a reference to that object. One way to make a object eligible for garbage collection is by assigning it a null value,
Object obj=null
In the code you have provided the object s is never assigned a null value nor does it it form a isolated island of objects.
Therefore according to me the object should not be garbage collected before statement labeled 4.
 
Kedar Dravid
Ranch Hand
Posts: 333
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
void X() {
String r = new String("abc");
String s = new String("abc");//obj
r = r+1; //1
r = null; //2
s = s + r; //3
} //4

At line 3, the object originally held in s ("abc") is reassigned, so s points to a String with the value "abc abc".
So, after line 3 (and before line 4), the object originally held in s is eligible for garbage collection.
[ March 11, 2005: Message edited by: Kedar Dravid ]
 
Ravi Raj
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
's' does not have "abc abc". it would have "abcnull". can someone explain how it is eligible for gc.

RR
 
Mike Gershman
Ranch Hand
Posts: 1272
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String "abcnull" is a new object. When s refers to "abcnull", it no longer refers to the "abc" string created in line "obj", so that object is eligible for gc right after line 3.
 
Mathangi Shankar
Ranch Hand
Posts: 56
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mike,

Thanks for the solution.

Mathangi.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic