Sunday, August 25, 2013

Why is a String immutable?

I have often searched long and hard to find answers to questions on Multithreading and immutability. Why is an immutable object considered thread safe? Why are Strings immutable in the first place? I finally found the answer to the above question in Kathy Sierra's book.

Consider a typical Java application. It is almost commonplace that large amounts of String literals are used and these tend to occupy lot of memory. To make this efficient JVM has set aside a special area of memory called "String constant pool". When the compiler encounters a String literal, the JVM checks to see if it already exists. If a match is found then the reference to the new literal is directed to the existing String and no new String literal object is created. (The existing String simply has an additional reference). This is why Strings are immutable. A String literal can have several references pointing to it. Of course one can always override this behavior right? Then this whole "constant pool" model fails.  Well we cannot do it, because String class is declared final. Hence String object methods cannot be overridden.

No comments:

Post a Comment