Skip to content

Instantly share code, notes, and snippets.

@misTrasteos
Last active January 26, 2022 16:11
Show Gist options
  • Save misTrasteos/0aec7863d7df445156dfddaaaf828f75 to your computer and use it in GitHub Desktop.
Save misTrasteos/0aec7863d7df445156dfddaaaf828f75 to your computer and use it in GitHub Desktop.
Java Intern Strings Example
///usr/bin/env jbang "$0" "$@" ; exit $?
import java.util.List;
import java.util.LinkedList;
public class InternStringsExample {
public static void main(String... args) throws Exception {
List<String> strings = new LinkedList<String>();
for(int i=0; i<1_000_000; i++)
strings.add( "Visit Burgos!".intern() );
//strings.add( new String("Visit Burgos") );
Thread.currentThread().join();
}
}

Intern Strings Example

With Intern Strings

jmap -histo:live pid | grep -i node
   1:       1000000       24000000  java.util.LinkedList$Node (java.base@17.0.1)

jmap -histo:live pid | grep -i string 
   5:          1645          39480  java.lang.String (java.base@17.0.1)

One million nodes are being allocated. Only few Strings are allocated (It should be just 1, but the JVM plays here too)

Without Intern Strings

jmap -histo:live pid | grep -i node  
   2:       1000000       24000000  java.util.LinkedList$Node (java.base@17.0.1)
jmap -histo:live pid | grep -i string
   1:       1001662       24039888  java.lang.String (java.base@17.0.1)
  49:             9            280  [Ljava.lang.String; (java.base@17.0.1) 

One million nodes are being allocated. One million String objects are being allocated. Your JVM may be runningn with -XX:+UseStringDeduplication, so underneath char[] will be reused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment