• Post Reply Bookmark Topic Watch Topic
  • New Topic

Will the string literal be garbage collected before JVM close?  RSS feed

 
Sriram Sharma
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I understand string concepts to some extent.
But, now I have a different question.
When we create a String like
String a = "Sample";
The String object "Sample" is available in the heap and a reference is created in the string pool as well apart from the variable reference.
Now when a code like this follows the above snippet...
a = null;
The object "Sample" still has a reference from the string pool and will be available in the heap without being garbage collected.
Now, my question is....
Once the method is executed and the control comes out of that method, will the reference from string pool to the "Sample" object be removed or the relevant string object has to wait till the JVM shutdown for it to be garbage collected?
(I assume that variable a is local to the method where it was created and not a class level variable)

Please guide me.

Regards,
Sriram
 
Stephan van Hulst
Saloon Keeper
Posts: 7991
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strings in the pool are always retained.
 
Sriram Sharma
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, the string literals will always be in the heap untill the JVM shuts down???
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. I've seen code where people were calling intern() on String objects all the time. That method puts a string in the string pool (even when it's not a literal). They thought it would help with performance and memory usage, because if there are strings with the same content they are stored in memory only once. In reality it caused a huge memory leak because all those strings were kept in memory all the time.

With string literals that won't be a big problem, because usually you don't have megabytes of string literals in your source code.
 
Sriram Sharma
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Thanks for the reply...

Regards,
Sriram
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!