String intern() and the String Pool
The JVM keeps a table of unique strings called the string pool. Every string literal comes from it, and intern() adds other strings to it. This page explains how the pool works, shows exactly when two strings are the same object, measures the memory interning saves and the time it costs, and covers the alternatives that are usually better.
Contents
What the string pool is
A Java String==equals
The string pool is a hash table inside the JVM, called the StringTable in HotSpot, that maps text to one canonical String
- When a class first uses a string literal, the JVM resolves it through the pool, so every
in every class of the program refers to the same object. Text blocks and compile-time constant expressions are literals too."hello" looks up the text ofs.intern() . If an equal string is already pooled it returns that one; otherwise it addss and returnss .s
Strings created at run time, by new StringStringBuildersubstring
| Source | Pooled? | Example |
|---|---|---|
| String literal or text block | Yes, always | "hello" |
| Constant expression (JLS 15.29) | Yes, folded by the compiler | "data" + "base""v" + 21 |
intern() | Yes, returns the pooled copy | input.intern() |
new String(...) | No, always a new object | new String("hello") |
Run-time concatenation, StringBuilder | No | prefix + id |
I/O, parsing, substringsplit | No | reader.readLine() |
Since Java 7 the pooled strings live in the ordinary heap, not in the old fixed-size PermGen area, so the pool can grow and unused entries can be garbage collected. Every example on this page ran on JDK 21.
When two strings are the same object
The program creates the text hello====
public class InternBasics {
public static void main(String[] args) {
String a = "hello"; // literal: from the string pool
String b = "hello"; // same literal: same pooled object
String c = new String("hello"); // always a new object on the heap
String d = c.intern(); // the pooled object with equal content
String block = """
hello"""; // a text block is a literal too
System.out.println("a == b " + (a == b));
System.out.println("a == c " + (a == c));
System.out.println("a.equals(c) " + a.equals(c));
System.out.println("a == c.intern() " + (a == d));
System.out.println("c == c.intern() " + (c == d));
System.out.println("a == text block " + (a == block));
System.out.println("a == Other.GREETING " + (a == Other.GREETING));
// Strings built at run time are new objects, even with the same content
String built = new StringBuilder("hel").append("lo").toString();
String fromChars = String.valueOf(new char[] {'h', 'e', 'l', 'l', 'o'});
System.out.println("a == built " + (a == built));
System.out.println("a == fromChars " + (a == fromChars));
System.out.println("a == built.intern() " + (a == built.intern()));
}
}
class Other {
static final String GREETING = "hello"; // literals are shared across classes
}
Output:
a == b true
a == c false
a.equals(c) true
a == c.intern() true
c == c.intern() false
a == text block true
a == Other.GREETING true
a == built false
a == fromChars false
a == built.intern() true
- The two literals are the same object, and so are the text block and the constant
in another class. The pool is shared by the whole JVM.Other.GREETING is a different object even thoughnew String("hello") is true.equals returns the pooled literal, which is whyc.intern() is true anda == c.intern() is false:c == c.intern() itself was not added, because an equal string was already there.c- Strings built with
or from aStringBuilder are new objects. Interning one of them returns the literal.char[]
Constant expressions: what the compiler folds
The compiler evaluates some expressions itself and stores only the result in the class file. Whether an expression qualifies depends on small details, such as whether a variable is final
public class ConstantFolding {
static final String DATA = "data"; // constant variable
static final String LATE = String.valueOf("data"); // final, but not a constant
static String notFinal = "data";
public static void main(String[] args) {
String db = "database";
final String data = "data"; // final local with a literal: constant
String base = "base"; // ordinary variable
final String computed = data.substring(0); // final, but computed at run time
show("\"data\" + \"base\"", "data" + "base" == db);
show("data + \"base\" (final)", data + "base" == db);
show("DATA + \"base\" (static)", DATA + "base" == db);
show("\"data\" + base", "data" + base == db);
show("LATE + \"base\"", LATE + "base" == db);
show("notFinal + \"base\"", notFinal + "base" == db);
show("computed + \"base\"", computed + "base" == db);
show("(\"data\" + base).intern()", ("data" + base).intern() == db);
// Other constant expressions fold too
show("\"v\" + 21", "v" + 21 == "v21");
show("true ? \"a\" : \"b\"", (true ? "a" : "b") == "a");
show("\"x\" + 'y'", "x" + 'y' == "xy");
}
static void show(String label, boolean sameObject) {
System.out.printf("%-26s %b%n", label, sameObject);
}
}
Output:
"data" + "base" true
data + "base" (final) true
DATA + "base" (static) true
"data" + base false
LATE + "base" false
notFinal + "base" false
computed + "base" false
("data" + base).intern() true
"v" + 21 true
true ? "a" : "b" true
"x" + 'y' true
- Two literals joined with
are folded into the literal+ , so the result is the pooled object."database" - A
variable initialized with a constant expression is a constant variable, local orfinal , and folds the same way:static anddata + "base" are both true.DATA + "base" isLATE but is initialized with a method call, andstatic final iscomputed but callsfinal . Neither is a constant, so both concatenations happen at run time and create new objects. A non-final variable never folds.substring- Numbers, characters and conditional expressions with constant operands also fold:
is the same object as"v" + 21 ."v21"
This is why code that compares with ==
The pool lives in the heap and is garbage collected
A common worry is that interning fills a permanent area until the JVM crashes. The program checks the table size, then interns a string built at run time, drops all references to it and asks for garbage collection, with a WeakReference
import java.lang.management.ManagementFactory;
import java.lang.ref.WeakReference;
import com.sun.management.HotSpotDiagnosticMXBean;
public class PoolInHeap {
public static void main(String[] args) {
HotSpotDiagnosticMXBean vm = ManagementFactory.getPlatformMXBean(
HotSpotDiagnosticMXBean.class);
System.out.println("StringTableSize = " + vm.getVMOption("StringTableSize").getValue());
// An interned string that nothing else refers to can be garbage collected
WeakReference<String> ref = new WeakReference<>(makeInterned(4711));
System.out.println("before GC, still in pool? " + (ref.get() != null));
for (int i = 0; i < 5 && ref.get() != null; i++) {
System.gc();
}
System.out.println("after GC, collected? " + (ref.get() == null));
// A literal is held by the class's constant pool, so it stays
WeakReference<String> literal = new WeakReference<>("a literal in this class");
System.gc();
System.out.println("literal collected? " + (literal.get() == null));
// intern() of an equal string after collection returns a fresh pooled object
String again = makeInterned(4711);
System.out.println("re-interned: " + again + ", same as a new intern() call? "
+ (again == makeInterned(4711)));
}
// Built at run time from a parameter, so it is not a literal of this class
static String makeInterned(int id) {
return ("session-" + id).intern();
}
}
Output:
StringTableSize = 65536
before GC, still in pool? true
after GC, collected? true
literal collected? false
re-interned: session-4711, same as a new intern() call? true
is the number of buckets in the hash table, 65536 by default on JDK 21. HotSpot resizes the table as it fills, so the option rarely needs changing;StringTableSize prints how full it is when the JVM exits.-XX:+PrintStringTableStatistics- The interned
was collected once nothing referred to it. The pool holds its entries weakly, so interning many short-lived values does not leak memory.session-4711 - The literal was not collected, because the class that uses it keeps it alive for as long as the class is loaded.
- After collection, interning equal text again simply pools a new object, and later calls return that one.
The string built in makeInterned"session-" + 4711
What interning saves: duplicate values
Interning pays off when a program holds many strings with few distinct values, like a country code column loaded from a file. The program keeps a million such strings twice, once as separate objects and once interned.
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import java.util.List;
public class InternMemory {
static long usedMb() {
Runtime rt = Runtime.getRuntime();
System.gc();
return (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024);
}
public static void main(String[] args) {
// 1,000,000 strings that contain only 4 distinct values, like a "country" column
String[] codes = {"IN", "US", "DE", "BR"};
long before = usedMb();
List<String> plain = new ArrayList<>();
for (int i = 0; i < 1_000_000; i++) {
plain.add(new String(codes[i % 4])); // a fresh object each time
}
long plainMb = usedMb() - before;
List<String> interned = new ArrayList<>();
for (int i = 0; i < 1_000_000; i++) {
interned.add(new String(codes[i % 4]).intern()); // collapses to 4 objects
}
long internedMb = usedMb() - before - plainMb;
Set<String> objects = Collections.newSetFromMap(new IdentityHashMap<>());
objects.addAll(interned); // counts objects, not values
long distinctInterned = objects.size();
System.out.println("distinct objects, interned list: " + distinctInterned);
System.out.println("approx. memory, plain list: " + plainMb + " MB");
System.out.println("approx. memory, interned list: " + internedMb + " MB");
System.out.println(plain.size() + interned.size() + " strings kept alive");
}
}
Output (memory figures are approximate and vary with the JVM and its settings):
distinct objects, interned list: 4
approx. memory, plain list: 28 MB
approx. memory, interned list: 5 MB
2000000 strings kept alive
- The interned list holds a million references to just 4 string objects. An
-based set counts objects rather than values, which is why it reports 4.IdentityHashMap - The plain list used about 28 MB and the interned list about 5 MB. The remaining 5 MB is the list's own array of references, which both lists need.
- Each separate two-letter string costs an object header, a hash field, a length and its own byte array: more than 20 bytes for 2 bytes of text. Short duplicated strings are where the overhead is largest.
What interning costs, and the alternatives
intern()HashMapConcurrentHashMap
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.UnaryOperator;
public class InternCost {
public static void main(String[] args) {
int n = 1_000_000;
String[] fewDistinct = new String[n];
String[] allUnique = new String[n];
for (int i = 0; i < n; i++) {
fewDistinct[i] = new String("status-" + (i % 10));
allUnique[i] = new String("order-" + i);
}
System.out.println("1,000,000 strings with 10 distinct values:");
time("String.intern()", fewDistinct, String::intern);
Map<String, String> map = new HashMap<>();
time("HashMap pool", fewDistinct, s -> map.computeIfAbsent(s, k -> k));
Map<String, String> concurrent = new ConcurrentHashMap<>();
time("ConcurrentHashMap pool", fewDistinct, s -> concurrent.computeIfAbsent(s, k -> k));
System.out.println("1,000,000 unique strings:");
time("String.intern()", allUnique, String::intern);
Map<String, String> map2 = new HashMap<>();
time("HashMap pool", allUnique, s -> map2.computeIfAbsent(s, k -> k));
}
// Best of 3 runs; later runs find every value already pooled
static void time(String name, String[] values, UnaryOperator<String> pool) {
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
for (String v : values) {
pool.apply(v);
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-24s %6.1f ms%n", name, best / 1e6);
}
}
Output (rough comparison on a 2-CPU Linux machine, JDK 21; times vary between runs):
1,000,000 strings with 10 distinct values:
String.intern() 66.3 ms
HashMap pool 14.0 ms
ConcurrentHashMap pool 10.7 ms
1,000,000 unique strings:
String.intern() 420.3 ms
HashMap pool 18.3 ms
- With 10 distinct values, both map-based pools were several times faster than
. The map lookup is ordinary Java code that the JIT compiles inline.intern() - With a million unique values,
was more than ten times slower than theintern() , because every call adds a new entry to the native table. Interning mostly unique values, such as order IDs or free text, costs time and saves nothing.HashMap - A map you own can also be cleared, sized and scoped to one data set, and a
is safe to share between threads.ConcurrentHashMap
The JVM can also save the memory without changing identity. With -XX:+UseStringDeduplicationStringDeduplicationAgeThreshold
Identity traps
The real danger of the pool is that it makes ====Scannersplit
import java.util.Scanner;
public class IdentityTraps {
public static void main(String[] args) {
// Works with literals, so it passes a quick test...
System.out.println("isAdmin(\"admin\") with a literal: " + isAdmin("admin"));
// ...but fails with the same text read at run time
Scanner in = new Scanner("admin guest");
String typed = in.next();
System.out.println("typed = \"" + typed + "\", isAdmin: " + isAdmin(typed)
+ ", equals: " + "admin".equals(typed));
String fromSplit = "user=admin".split("=")[1];
System.out.println("from split, isAdmin: " + isAdmin(fromSplit));
// Literals are shared JVM-wide, so locking on one shares the lock with any other code
System.out.println("Library.LOCK == \"lock\": " + (Library.LOCK == "lock"));
}
static boolean isAdmin(String role) {
return role == "admin"; // compares identity: a bug
}
}
class Library {
static final String LOCK = "lock"; // synchronized (LOCK) would be shared
}
Output:
isAdmin("admin") with a literal: true
typed = "admin", isAdmin: false, equals: true
from split, isAdmin: false
Library.LOCK == "lock": true
is true because both sides are the pooled literal. The typed and the split value are new objects, so the same check returns false, whileisAdmin("admin") returns true.equals- Do not "fix" this by interning the input so that
works. It is slower than== and breaks as soon as one caller forgets. Compare text withequals , as described on theequalsstring comparison page . - Because literals are shared JVM-wide,
is the same object as any otherLibrary.LOCK literal. Code that does"lock" then shares its lock with unrelated code that happens to use the same literal. Lock on a privatesynchronized (LOCK) instead.new Object()
When to intern
| Situation | Do this |
|---|---|
| Comparing two strings | a.equals(b)== |
| Many long-lived strings, few distinct values | A HashMapConcurrentHashMapintern() |
| Mostly unique values | Do not intern |
| Memory full of duplicate strings, no code changes possible | -XX:+UseStringDeduplication |
| Values from a small fixed set | An enum |
| A lock object | private final Object lock = new Object() |
To find duplicate strings in a real application, take a heap dump and look at the duplicate strings report of a heap analyzer. For more on string memory and speed, see