Memory Benefits and Trade-offs
You'll learn how the string intern pool saves memory for duplicates but can cause leaks when overused with unique strings.
The Double-Edged Sword of Interning
The intern pool is like a shared warehouse for strings. When multiple parts of your application use the same literal (like "hello"), Java stores only one copy in the pool and hands out references to it. This is fantastic for memory—imagine a configuration file with thousands of "true" and "false" values. Without interning, you'd have thousands of duplicate objects cluttering the heap.
However, here's the catch: the intern pool lives in a special memory area that's harder to clean up. If you call intern() on thousands of unique user-generated strings (like unique usernames or dynamic URLs), you're stuffing the pool with strings that will never be reused. These strings stick around much longer than regular heap objects, potentially for the entire JVM lifetime.
When Interning Helps
// These all share ONE object in memory
String s1 = "config";
String s2 = "config";
String s3 = "config";
Memory saved: massive when literals repeat frequently.
When Interning Hurts
// DON'T do this with unique user input!
for (int i = 0; i < 100000; i++) {
String unique = ("user_" + i).intern(); // Memory leak risk!
}
Each interned string stays in the pool indefinitely, bloating memory instead of being garbage-collected normally.
The Rule of Thumb
Intern strings that repeat frequently across your application. Avoid interning strings that are unique or rarely reused—let them live on the regular heap where they can be garbage-collected freely.
Key Takeaway: The intern pool drastically reduces memory for duplicate strings, but interning unique strings prevents garbage collection and causes memory leaks—use it strategically only for repeated values.