Video in progress

Senior ☕ Core Java

If identical Strings take up a large part of memory in a heap dump, what do you do?

First find the source (JSON parsing, codes coming from the DB, logs). Then choose: your own canonical cache or intern(), G1's String deduplication, or using an enum/ID instead of a String. Java 9+ compact strings already store Latin-1 text twice as compactly.

📖 Answer

In Eclipse MAT, "Java Basics → Find Duplicate Strings", or the allocation profile in JFR, will show it: for example, 2 million copies of "TASHKENT", each about 48 bytes (with compact strings and compressed oops). The source is usually columns where the same values come back a lot (city, currency, status) or JSON keys.

The options, starting with the cheapest:

  1. Turn the meaning into a type. If currency always has 5 possible values, use an enum Currency. The memory problem goes away on its own, and type safety is a bonus.

  2. Your own canonical cache, for known, bounded values:

private static final ConcurrentHashMap<String, String> CITIES = new ConcurrentHashMap<>();
static String canonical(String s) {
    String prev = CITIES.putIfAbsent(s, s);
    return prev != null ? prev : s;
}

Don't do this with unbounded input (user text): the cache itself turns into a leak.

  1. String.intern() is the JVM's native table; since Java 7 Strings are on the heap and the GC cleans them. But there's the table size (-XX:StringTableSize) and contention; measure before using it widely.

  2. String deduplication (-XX:+UseStringDeduplication; at first only G1, and from Java 18 with other GCs too): the code doesn't change, and the GC merges identical byte[]s in the background. It only affects objects that have gone through several GC cycles; it does nothing for short-lived Strings.

One more detail: in Java 9+, a String holds a byte[] plus a coder. If there are only Latin-1 characters, one character is 1 byte. Uzbek Latin text (o', g', with a plain apostrophe) fits in Latin-1; a single Cyrillic character or ʻ (U+02BB) moves the whole string to UTF-16 and doubles its size.

After each change, compare the heap dump or jcmd <pid> GC.heap_info again: you settle it with numbers, not guesses.