Common Use Cases and Anti-patterns for String intern()
You'll learn when to use intern() effectively and when it becomes a performance liability.
The Right Use Cases
The intern() method shines when you have a bounded, predictable set of canonical strings that will be compared frequently. Think of scenarios like:
- Configuration keys or enum-like constants loaded from external sources (e.g., parsing a limited set of status codes: "PENDING", "APPROVED", "REJECTED")
- Small, known vocabularies such as country codes, currency symbols, or protocol commands
- Deduplicated identifiers in data processing where the same values repeat often
In these cases, interning saves memory by ensuring only one copy exists, and enables fast == comparisons instead of equals().
// GOOD: Small, repeated set of values
String status = getUserStatus(); // from database
String canonical = status.intern();
if (canonical == "APPROVED") { /* fast comparison */ }
The Anti-patterns
Never intern unbounded or user-generated strings. This pollutes the intern pool (which isn't garbage-collected in older JVMs, and even in modern Metaspace grows without limit):
// BAD: User input - unbounded growth!
String username = getUserInput().intern(); // DON'T
// BAD: Dynamic data with infinite variations
String timestamp = Instant.now().toString().intern(); // DON'T
These anti-patterns cause memory leaks (pool bloat) and performance degradation (pool lookup becomes expensive as it grows).
Another anti-pattern: interning in tight loops for no reason, adding unnecessary overhead when regular equals() would suffice.
Key Takeaway:
Use intern() only for small, well-defined sets of repeating strings; avoid it for unbounded, dynamic, or user-generated data to prevent pool pollution and memory bloat.