String Deduplication is an additional feature of G1 Garbage collector, introduced in JDK 8 – 20th update. Its aim is to reduce the Java Heap Live data set by deleting the duplicate instances of a String Object.
How it works
To enable this feature in Java 8 and beyond, use below options:
$ java -Xmx256m -XX:+UseG1GC -XX:+UseStringDeduplication
It basically works by deleting the duplicate instances of a String in the heap. When we say duplicate instance, it means string1.equals(string2) is ‘true’, technically it finds another String by comparing their Hashcodes. If there are String that have the same Hashcodes, then it compares them char by char.
In a large application, where the heap is relatively large, enabling String Deduplication is proven to be quite useful in terms of managing the heap space. Lets analyze the below snapshots:
It is clearly evident from both the Heap usage graphs that by just enabling the String Deduplication in G1, there is a big drop in the Heap consumption by the application. In first image, heap memory maxes upto 1 GB, whereas in second image, it is hardly crossing 500MB.