← Recipes

Many Duplicate Strings

Reduce duplicate string backing storage in allocation-heavy text workloads.

Flags

-XX:+UseStringDeduplication-XX:+UseG1GC

-XX:+UseStringDeduplication asks G1 to identify strings with equal contents and share their backing storage where possible. It is useful only when duplicates are common enough to justify the extra GC work.

Flag details

-XX:+UseG1GC
Selects G1, the collector that supports HotSpot string deduplication in this recipe.
-XX:+UseStringDeduplication
Enables a G1 feature that looks for different String objects with identical character contents and shares backing storage where possible.
-Xlog:gc*,stringdedup=info
Logs both GC activity and string deduplication statistics so you can see whether the feature is saving memory or just adding overhead.

How G1 string deduplication works

G1 can inspect candidate strings during GC work and place their backing arrays into a deduplication table. When another string has the same contents, the JVM can make both strings share the same backing storage. The String objects still exist; the saving comes from avoiding duplicate character storage.

This is useful only when repeated text is common enough to offset the CPU and bookkeeping cost. It often helps text-heavy heaps with repeated keys, identifiers, codes, and labels.

When to use it

Use this for JSON/XML processing, log aggregation, catalogs, caches, indexing systems, and services with many repeated names, keys, IDs, or status values.

Java version support

G1 String Deduplication is available with G1 in Java 8 update releases and later. The recipe examples use Java 9+ unified logging for the stringdedup tag.

Related JEPs

Examples

java -XX:+UseG1GC -XX:+UseStringDeduplication \
  -Xmx4g \
  -Xlog:gc*,stringdedup=info:file=logs/stringdedup.log:time,uptime,level,tags \
  -jar text-heavy-app.jar

Use the log tag while evaluating the feature; remove extra logging later if it is too noisy.

Verify

Compare heap retained size and GC CPU before and after enabling the flag. It is not free, so keep it only when memory savings are visible.