Showing posts with label pool. Show all posts
Showing posts with label pool. Show all posts

Sunday, February 12, 2012

Java string pool and intern

Two ways of creating string are
1) String s ="hello"; No. of string literal = 1 i.e. "hello" - No. of String objects on heap = 0

2) String s= new String("hello"); - No. of string literals =1 and No. of string objects =1

Java maintains a string pool of "LITERALS" and not of objects.

Advantage of string pooling: 1) Reduced memory usage*(PermGenSpace Issue) 2) Faster Comparision i.e == comparision 3) Faster lookup
Disadvantages: 1) Overhead maintaining pool

How to pool String objects? Use Intern() on a string to add it to the pool. Downside of interning: 1) You may forget to intern some strings and compare them by == leading to unexpected results.

*Interning large number of strings is a problem again. The internalized strings go to the Permanent Generation, which is an area of the JVM that is reserved for non-user objects, like Classes, Methods and other internal JVM objects. The size of this area is limited, and is usually much smaller than the heap. Calling intern() on a String has the effect of moving it out from the heap into the permanent generation, and you risk running out of PermGen space.