Wednesday, 29 July 2015

String interning

String interning : intern()

Java by default doesn't put all String object into String pool, instead we have flexibility to store any arbitrary String object in String pool explicitly.

java.lang.String.intern() method used to put String object to String pool.

String creation using String literal notation of Java is automatically call intern() method to put that object into String pool, provided it was not present in the pool already.

But in case of new, interning doesn't happen automatically, until you call intern() method on that object.

Double quoted literal is known as String literal and the cache which stored these String instances are known as String pool.

    String a = "StringLiteral";
    String b = "StringLiteral";
    System.out.println(a == b);  // True
    String c = new String("StringHeap");
    String d = new String("StringHeap");
    System.out.println(c == d); // False a different reference!

    String e = "JDK";
    String f = new String("JDK").intern();
    System.out.println(e == f); //True :String moved to constant pool!

Points to remember:

String pool was located in permgen area of heap up-to Java 1.6, but in Java 1.7 updates it’s moved to main heap area.

Earlier since it was in PermGen space, it was always a risk to create too many String object (java.lang.OutOfMemory: permgen space), because it’s a very limited space, default size 64 MB and used to store class metadata e.g. .class files.

Now because String pool is moved to a much larger memory space, it's much safer.

By the way, don't misuse memory here, always try to minimize temporary String object e.g. "a", "b" and then "ab". So don't forget to use StringBuffer and StringBuilder for string concatenation; it will reduce number of temporary Object in String pool.

Compare two String object using equals() method and never compare them using == operator, because we never know which one is coming from pool and which one is created using new() operator.

Perm space

Perm space is used to keep information for loaded classes and few other advanced features like String Pool, which usually get created by String.intern() methods.

PermGen Space speeds up our String equality searching.

As your application (number of classes) will grow this space shall get filled quickly, since the garbage collection on this Space is not much effective to clean up as required, you quickly get Out of Memory: perm gen space error. After then, no application shall run on that machine effectively even after having a huge empty JVM.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...