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

Question of garbage collection

 
Carfield Yim
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
However, as String will pool the constant String for other string object to use. Thus I think there should be no String object are eligible for GC, am I right?
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strings that are created on the heap are eligible for garbage collection.
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On the heap

explanation, example, please...
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s1 = new String("Java"); // on the heap
String s2 = "Is Great"; // in the pool
All the methods of String that return a String object create a new String on the heap (if a new String object is needed).
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just my $0.2...
A string created on the heap can be put into the pool by invoking intern().
Taking Thomas' example,
//s1 references a string object on the heap
String s1 = new String("Java");
//s2 references a string object in the pool
String s2 = "Is Great";
//s1 now references a string object containing the same character sequence as before, but located in the pool
s1 = s1.intern(); // in the pool
//s3 references the same string object as s1 (in the pool)
String s3 = "Java";
//this reference comparison yields true
System.out.println(s1 == s3);
 
Ruff Young
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Valentin for pointing.
 
Ruff Young
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am wondering that "s1" is no longer in heap?
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The String is still on the heap but is now eligible for garbage collection since nothing references it.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic