Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can we delete a String Object from JVM String Pool?

 
Aakash Parashar
Ranch Hand
Posts: 123
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can we delete a String Object from JVM String Pool?
 
Rob Spoor
Sheriff
Pie
Posts: 20548
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope. If you don't want a String to be in the String pool, you must make sure it doesn't get put into it in the first place: don't use it as a String literal, and don't intern() it.
 
Aakash Parashar
Ranch Hand
Posts: 123
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:Nope. If you don't want a String to be in the String pool, you must make sure it doesn't get put into it in the first place: don't use it as a String literal, and don't intern() it.


We are using some java libraries which only return String, and we want to delete those String once used, because they are too large to be occupied in memory, causing OutOfMemoryError.
 
Rob Spoor
Sheriff
Pie
Posts: 20548
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure they are the reason for the memory error? String literals don't take up much memory, unless they are either very very long or very very numerous.

Are you even sure they are String literals, and not non-interned Strings? These should be garbage collected as usual.

Part of your problem may be that you are still holding a reference to them, or perhaps to their internal char[]. When you call substring on a String, that substring shares the original String's char[]. If the substring is much smaller than the original, that is a waste of memory. This is one of the few cases where using copying the String makes sense. So if this is the case, use the following to create substrings:
This will create a new String that does not share the char[], and therefore this char[] can be garbage collected too.
 
Aakash Parashar
Ranch Hand
Posts: 123
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Problem solved by reducing the number of instances of Spring Objects. Used StringBuffer and CharacterSequence in place of String where ever it was possible.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49405
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why StringBuffer rather than StringBuilder?
 
Aakash Parashar
Ranch Hand
Posts: 123
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
StringBuilder will be preferable when you use java 5 or higher version.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic