What Is Java String Interning

What is Java String interning?

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()

Basically doing String.intern() on a series of strings will ensure that all strings having same contents share same memory. So if you have list of names where 'john' appears 1000 times, by interning you ensure only one 'john' is actually allocated memory.

This can be useful to reduce memory requirements of your program. But be aware that the cache is maintained by JVM in permanent memory pool which is usually limited in size compared to heap so you should not use intern if you don't have too many duplicate values.


More on memory constraints of using intern()

On one hand, it is true that you can remove String duplicates by
internalizing them. The problem is that 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.

--
From: http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html


From JDK 7 (I mean in HotSpot), something has changed.

In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

-- From Java SE 7 Features and Enhancements

Update: Interned strings are stored in main heap from Java 7 onwards. http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes

When should we use intern method of String on String literals

Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values.

Since interning is automatic for String literals, the intern() method is to be used on Strings constructed with new String()

Using your example:

String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();
String s4 = new String("Rakesh");
String s5 = new String("Rakesh").intern();

if ( s1 == s2 ){
System.out.println("s1 and s2 are same"); // 1.
}

if ( s1 == s3 ){
System.out.println("s1 and s3 are same" ); // 2.
}

if ( s1 == s4 ){
System.out.println("s1 and s4 are same" ); // 3.
}

if ( s1 == s5 ){
System.out.println("s1 and s5 are same" ); // 4.
}

will return:

s1 and s2 are same
s1 and s3 are same
s1 and s5 are same

In all the cases besides of s4 variable, a value for which was explicitly created using new operator and where intern method was not used on it's result, it is a single immutable instance that's being returned JVM's string constant pool.

Refer to JavaTechniques "String Equality and Interning" for more information.

java string concatenation and interning

The first part of your question is simple: Java compiler treats concatenation of multiple string literals as a single string literal, i.e.

"I Love" + " Java"

and

"I Love Java"

are two identical string literals, which get properly interned.

The same interning behavior does not apply to += operation on strings, so b1 and b2 are actually constructed at run-time.

The second part is trickier. Recall that b1.intern() may return b1 or some other String object that is equal to it. When you keep a1 and a2, you get a1 back from the call to b1.intern(). When you comment out a1 and a2, there is no existing copy to be returned, so b1.intern() gives you back b1 itself.

The return of String.intern() explained

s2.intern() would return the instance referenced by s2 only if the String pool didn't contain a String whose value is "java" prior to that call. The JDK classes intern some Strings before your code is executed. "java" must be one of them. Therefore, s2.intern() returns the previously interned instance instead of s2.

On the other hand, the JDK classes did not intern any String whose value is equal to "Cattie & Doggie", so s1.intern() returns s1.

I am not aware of any list of pre-interned Strings. Such a list will most likely be considered an implementation detail, which may vary on different JDK implementations and JDK versions, and should not be relied on.

What is the purpose of Java's String.intern()?

There are essentially two ways that our String objects can enter in to the pool:

  • Using a literal in source code like "bbb".
  • Using intern.

intern is for when you have a String that's not otherwise from the pool. For example:

String bb = "bbb".substring(1); // substring creates a new object

System.out.println(bb == "bb"); // false
System.out.println(bb.intern() == "bb"); // true

Or slightly different:

System.out.println(new String("bbb").intern() == "bbb"); // true

new String("bbb") does create two objects...

String fromLiteral = "bbb";                     // in pool
String fromNewString = new String(fromLiteral); // not in pool

...but it's more like a special case. It creates two objects because "bbb" refers to an object:

A string literal is a reference to an instance of class String [...].

Moreover, a string literal always refers to the same instance of class String.

And new String(...) creates a copy of it.

However, there are many ways String objects are created without using a literal, such as:

  • All the String methods that perform some kind of mutation. (substring, split, replace, etc.)
  • Reading a String from some kind of input such as a Scanner or Reader.
  • Concatenation when at least one operand is not a compile-time constant.

intern lets you add them to the pool or retrieve an existing object if there was one. Under most circumstances interning Strings is unnecessary but it can be used as an optimization because:

  • It lets you compare with ==.
  • It can save memory because duplicates can be garbage collected.

Difference between String intern method and normal string creation

The difference is that the initialization way of the variable that decides where to save the variable ;

  1. if it has the same value and same initialization method and initialized using new keyword - it will save it in heap and will save each variable as new object even if it has same value.
  2. if it has the same value and same initialization method and initialized directly - it will reference it in JVM pooled memory .

String Interning Oracle reference .

There are two ways to construct a string: implicit construction by assigning a string literal or explicitly creating a String object via the new operator and constructor. For example

String s1 = "Hello";              // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object

Java has provided a special mechanism for keeping the String literals - in a so-called string common pool. If two string literals have the same contents, they will share the same storage inside the common pool. This approach is adopted to conserve storage for frequently-used strings. On the other hand, String objects created via the new operator and constructor are kept in the heap. Each String object in the heap has its own storage just like any other object .

Sample Image

s1 == s1;         // true, same pointer
s1 == s2; // true, s1 and s1 share storage in common pool
s1 == s3; // true, s3 is assigned same pointer as s1
s1.equals(s3); // true, same contents
s1 == s4; // false, different pointers
s1.equals(s4); // true, same contents
s4 == s5; // false, different pointers in heap
s4.equals(s5); // true, same contents

Important Notes:

  1. In the above example, I used relational equality operator '==' to compare the references of two String objects. This is done to demonstrate the differences between string literals sharing storage in the common pool and String objects created in the heap. It is a logical error to use (str1 == str2) in your program to compare the contents of two Strings.
  2. String can be created by directly assigning a String literal which is shared in a common pool. It is uncommon and not recommended to use the new operator to construct a String object in the heap.

How does string interning work in Java 7+?

There's a thing called String Memory Pool in java, when you declare:

String str1="abc";

It goes to that memory pool and not on the heap. But when you write:

String str2=new String("abc");

It creates a full fledged object on the heap, If you again write:

String str3 = "abc"; 

It won't create any more object on the pool, it will check the pool if this literal already exists it will assign that to it. But writing:

String str4 = new String("abc");

will again create a new object on the heap

Key point is that:

A new object will always be created on the heap as many times as you keep writing:

new String("abc");

But if you keep assigning the Strings directly without using the keyword new, it will just get referenced from the memory pool (or get created if not present in the memory pool)

intern() method finds if the string is present in the memory pool if it is not it adds it to the memory pool and returns a reference to it. so after using this method the String reference of yours is not pointing to any object on the heap, it is pointing to an object in the String Memory Pool (Also, note that the memory pool only contains unique strings).

Is it good practice to use java.lang.String.intern()?

When would I use this function in favor to String.equals()

when you need speed since you can compare strings by reference (== is faster than equals)

Are there side effects not mentioned in the Javadoc?

The primary disadvantage is that you have to remember to make sure that you actually do intern() all of the strings that you're going to compare. It's easy to forget to intern() all strings and then you can get confusingly incorrect results. Also, for everyone's sake, please be sure to very clearly document that you're relying on the strings being internalized.

The second disadvantage if you decide to internalize strings is that the intern() method is relatively expensive. It has to manage the pool of unique strings so it does a fair bit of work (even if the string has already been internalized). So, be careful in your code design so that you e.g., intern() all appropriate strings on input so you don't have to worry about it anymore.

(from JGuru)

Third disadvantage (Java 7 or less only): interned Strings live in PermGen space, which is usually quite small; you may run into an OutOfMemoryError with plenty of free heap space.

(from Michael Borgwardt)

Is string interning really useful?

No, Java and .NET don't do it "automatically with all strings". They (well, Java and C#) do it with constant string expressions expressed in bytecode/IL, and on demand via the String.intern and String.Intern (.NET) methods. The exact situation in .NET is interesting, but basically the C# compiler will guarantee that every reference to an equal string constant within an assembly ends up referring to the same string object. That can be done efficiently at type initialization time, and can save a bunch of memory.

It doesn't happen every time a new string is created.

(On the string immutability front, I for one am extremely glad that strings are immutable. I don't want to have to take a copy every time I receive a parameter etc, thank you very much. I haven't seen it make string processing tasks harder, either...)

And as others have pointed out, looking up a string in a hash table isn't generally an O(n) operation, unless you're incredibly unlucky with hash collisions...

Personally I don't use string interning in user-land code; if I want some sort of cache of strings I'll create a HashSet<string> or something similar. That can be useful in various situations where you expect to come across the same strings several times (e.g. XML element names) but with a simple collection you don't pollute a system-wide cache.



Related Topics



Leave a reply



Submit