Interning
Interning stores one shared copy of a value and returns that copy for every equal value. In Java, String.intern() is the built-in intern for strings. You can intern other types with a map.
Detailed Explanation
Canonical form means "these two equal values are the same object". Enums intern by design: Status.OPEN is a single instance. Strings intern through the pool. You might intern parsed tokens (IN, OUT) so maps can use == and so you store one String per distinct token.
String.intern() is synchronized at the JVM level and can be a contention point. It also pins the string in the intern table. A hand-rolled intern (ConcurrentHashMap<String, String> with putIfAbsent) can be bounded or evicting; the native intern cannot.
For types that are not strings, a WeakHashMap or a Caffeine cache of canonical instances is the pattern. Guava's Interner did this. Equality must be correct or you will merge values that are not the same.
You reach for interning when a profiler shows millions of duplicate equal strings or objects, and the distinct count is small. You reach for it in compilers and parsers. You do not intern as a default style. You do not use intern to make == work in business logic; teach equals.
The cost of native intern on many unique strings is native/heap growth and slower allocation. The cost of a strong-map intern is a leak of every distinct value ever seen. Weak keys help only if nothing else retains the value (the map's value pointing at the key is a classic leak).
Integer interning exists for a small range (Integer.valueOf caches -128..127). == on Integer is a famous bug outside that range. Do not intern integers by hand to paper over ==.
Code Examples
public class Tokens {
static String internToken(String raw) {
return raw.trim().toUpperCase().intern(); // only if the set is tiny and closed
}
public static void main(String[] args) {
String a = internToken(" in ");
String b = internToken("IN");
System.out.println(a == b); // prints: true
System.out.println(a); // prints: IN
}
}import java.util.concurrent.ConcurrentHashMap;
public class Bounded {
private static final ConcurrentHashMap<String, String> CANON = new ConcurrentHashMap<>();
static String canon(String s) {
String prev = CANON.putIfAbsent(s, s);
return prev == null ? s : prev;
}
public static void main(String[] args) {
String a = canon(new String("x"));
String b = canon(new String("x"));
System.out.println(a == b); // prints: true
}
}Common Gotchas
Native `intern()` retains forever (from your point of view)
do not intern request bodies.
`Integer` cache is only -128..127
`Integer.valueOf(200) == Integer.valueOf(200)` is false.
`intern()` can contend
a `ConcurrentHashMap` intern may be faster for a hot small set.
A map intern must not have values that pin keys if you wanted weak keys
A map intern must not have values that pin keys if you wanted weak keys