Video in progress
If most of the heap is Strings, how can you save memory at the JVM level, and what do you change in the application?
Since Java 9, compact strings store Latin-1 text with 1 byte per character. G1 and some other collectors merge identical internal arrays with String deduplication. But the biggest win is usually at the application level: replacing repeated values with an enum, a dictionary or a canonical copy.
📖 Answer
If byte[] and java.lang.String are at the top of the heap histogram, that is the usual picture. The question is whether they repeat.
Compact strings (JDK 9, JEP 254) are on by default. Latin text takes 1 byte each, and only strings that have a character requiring UTF-16 take 2 bytes. In Uzbek Latin script, if the apostrophe ' is plain ASCII, it is 1 byte. But if ʻ (U+02BB) is used, the whole string becomes UTF-16. You can take this into account when choosing a data format.
String deduplication:
-XX:+UseStringDeduplication
-Xlog:stringdedup*=debug
The GC makes the internal arrays of Strings with identical content into a single one (the String objects themselves remain). At first it was only in G1; since JDK 18 it is in the other collectors too. It runs on a background thread and takes CPU, and it only pays off for repeated, long-lived strings.
Application-level solutions are often stronger:
- make fields like
status,country,currencyanenum, not aString; - if millions of identical keys/values are read from JSON, use Jackson's
InternCache/canonicalization settings or your own dictionary (a canonical copy through aMap<String,String>); - be careful with
String.intern(): in modern JDKs the string table is on the heap and tunable, but uncontrolled interning can still be a memory and CPU problem; - store IDs as
longorUUID, notString.
To measure: MAT's "Duplicate Strings" query on a heap dump shows which values repeat how many times. That list usually tells you exactly which field to change.
Sign up to mark studied questions and save your progress.