Alex Rivera | Logout

Real Life, Practical Example of Using String.intern() in Java?

Asked 2010-08-18T08:59:18.797
24

I've seen many primitive examples describing how String intern()'ing works, but I have yet to see a real-life use-case that would benefit from it.

The only situation that I can dream up is having a web service that receives a considerable amount of requests, each being very similar in nature due to a rigid schema. By intern()'ing the request field names in this case, memory consumption can be significantly reduced.

Can anyone provide an example of using intern() in a production environment with great success? Maybe an example of it in a popular open source offering?

Edit: I am referring to manual interning, not the guaranteed interning of String literals, etc.

Edit
Report

2 Answers

1

Not a complete answer but additional food for thought (found here):

Therefore, the primary benefit in this case is that using the == operator for internalized strings is a lot faster than use the equals() method [for not internalized Strings]. So, use the intern() method if you're going to be comparing strings more than a time or three.

answered 2010-08-18T09:07:18.873
1

Examples where interning will be beneficial involve a large numbers strings where:

  • the strings are likely to survive multiple GC cycles, and
  • there are likely to be multiple copies of a large percentage of the Strings.

Typical examples involve splitting / parsing a text into symbols (words, identifiers, URIs) and then attaching those symbols to long-lived data structures. XML processing, programming language compilation and RDF / OWL triple stores spring to mind as applications where interning is likely to be beneficial.

But interning is not without its problems, especially if it turns out that the assumptions above are not correct:

  • the pool data structure used to hold the interned strings takes extra space,
  • interning takes time, and
  • interning doesn't prevent the creation of the duplicate string in the first place.

Finally, interning potentially increases GC overheads by increasing the number of objects that need to be traced and copied, and by increasing the number of weak references that need to be dealt with. This increase in overheads has to be balanced against the decrease in GC overheads that results from effective interning.

answered 2010-08-18T10:36:33.667

Your Answer