String.intern() manages the internal pool, implemented on the basis of its own implementation, which has some special functions related to the GC. This is old code, but if it was reimplemented, it would use java.util.WeakHashMap . Weak links are a way to keep a pointer to an object without interfering with its collection. The right thing for a pool together, such as interned strings.
These interned strings collect garbage that can be demonstrated with the following Java code:
public class InternedStringsAreCollected { public static void main(String[] args) { for (int i = 0; i < 30; i ++) { foo(); System.gc(); } } private static void foo() { char[] tc = new char[10]; for (int i = 0; i < tc.length; i ++) tc[i] = (char)(i * 136757); String s = new String(tc).intern(); System.out.println(System.identityHashCode(s)); } }
This code creates the same string 30 times, interning it each time. Additionally, it uses System.identityHashCode() to show which hash code of Object.hashCode() would be returned to this interned string. When run, this code prints clear integer values, which means that you are not getting the same instance every time.
In any case, the use of String.intern() somewhat discouraged. This is a common static pool, which means that it easily turns into a bottleneck in multi-core systems. Use String.equals() to compare strings, and you will live longer and happier.
Thomas Pornin Mar 12 '10 at 13:45 2010-03-12 13:45
source share