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

Is my thinking correct?

 
Santosh Bapat
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String string1 = "Test";
String string2 = "Today";
string1 = null;
string1 = string2;
The object which string1 originally pointed to is eligible for garbage collection after these four lines?
 
Dave Vick
Ranch Hand
Posts: 3244
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Santosh
The subject of stoing literals and garbage collection has been raised at least a few million times.
Here is one thread with some info for you.

You can also try to
search for the answers.
 
alex earnshaw
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Santosh Bapat:
String string1 = "Test";
String string2 = "Today";
string1 = null;
string1 = string2;
The object which string1 originally pointed to is eligible for garbage collection after these four lines?

To my knowledge, "Test" will be eligible for garbage collection immediately after line 3. "Today" will be eligable for garbage collection only if both string1 and string2 are set to null or to other string objects.
HTH
Alex
 
Donald Yee
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by alex earnshaw:

To my knowledge, "Test" will be eligible for garbage collection immediately after line 3. "Today" will be eligable for garbage collection only if both string1 and string2 are set to null or to other string objects.
HTH
Alex

I believe that since the code is using string literals, "Test" is never eligible for collection.
The string literal is placed into the pool and as such has something always referencing it.
Now if the code said:
String string1 = new String("Test");
String string2 = new String("Today");
string1 = null;
string1 = string2;
then, the first object is eligible when string1 is set to null.
Of course if I'm wrong someone will correct me
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic