Ravi Gupta Ravi Gupta - 3 months ago 8
Java Question

Garbage collection behaviour for String.intern()

If I use String.intern() to improve performance as I can use "==" to compare interned string, will I run into garbage collection issues. How does the garbage collection mechanism of interned strings differ from normal strings ?

Answer

In fact, this not a garbage collection optimisation, but rather a string pool optimization. When you call String.intern(), you replace reference to your initial String with its base reference (the reference of the first time this string were encountered, or this reference if it is not yet known).

However, it will become a garbage collector issue once your string is of no more use in application, since the interned string pool is a static member of the String class and will never be garbage collected.

As a rule of thumb, i consider preferrable to never use this intern method and let the compiler use it only for constants Strings, those declared like this :

String myString = "a constant that will be interned";

This is better, in the sense it won't let you do the false assumption == could work when it won't.

Besides, the fact is String.equals underlyingly calls == as an optimisation, making it sure interned strings optimization are used under the hood. This is one more evidence == should never be used on Strings.

Comments