跳至主要内容

String Intern???

String Intern???

Today we explore a commonly asked interview question of Java String#intern()

Question

So the commonly asked question is: what is the output of following code (run using Java8) and explain why:

String s1 = new String("s1");
// notice this is `==`, is to compare address
System.out.println(s1.intern() == s1);
String s2 = new String("s") + new String("2");
// notice this is `==`, is to compare address
System.out.println(s2.intern() == s2);
Strig s3 = "s3";
// notice this is `==`, is to compare address
System.out.println(s3.intern() == s3);

Think a while before continue.

Answer

false
true
true

The explanation is a bit complex, so let us start with the Java doc of intern:

Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

After viewing the doc, we may be still not clear the differences between s1 and s2. Don’t be worried, let’s explore what the doc means by combining code.

As the doc says, if a string is not in string pool, it will be added and return reference to this string, i.e. the return value in this case will be same with original string:

s.intern() == s

which seems the case of s2.

In other words, s1 goes to another branch: the pool already had the same content string and return directly, i.e. the return value may be different with invoked string. And for s1 it is different as output shows.

What about s3? The short answer is the pool has the same content string and return it. And the s3 is the one in string pool.

In order to understand those behavior we have to understand the so called ‘String Pool’.

String Pool

What Is String Pool?

This is the first reason we are wondering: what exactly the string pool is?

By following the call stack of method call, we will follow from java code to cpp code (for which intern is a native method). Finally, we can find the following implementation code in HotSpot JVM:

oop StringTable::intern(Handle string_or_null, jchar* name,  
                        int len, TRAPS) {  
  unsigned int hashValue = java_lang_String::hash_string(name, len);  
  int index = the_table()->hash_to_index(hashValue);  
  oop string = the_table()->lookup(index, name, len, hashValue);  
  // Found  
  if (string != NULL) return string;  
  // Otherwise, add to symbol to table  
  return the_table()->basic_add(index, string_or_null, name, len, hashValue, CHECK_NULL);  
}

In short, the StringTable is a fixed size HashMap<hashcode, string> (If you are interested in more details, you may refer to this openjdk implementaion). So, we can just take the so-called ‘String Pool’ a HashMap.

What is In String Pool

Understand what is String Pool, we need to know what is in String Pool:

String s1 = "1";
String s2 = new String("2");
String s3 = "" + new String("3");
String s4 = new String("4") + new String("4");
String s5 = "1" + "2";
String s6 = "1" + 3;
  • literal strings and string-valued constant expressions are default in it"1" (so as s1), "2", "", "3", "4", "12"(s5), "13"(s6)
  • a string will promote to string pool after intern if not already exist

What should be noticed here is s5 & s6: they will be combined to string const by compiler, as this question described.

Where Is String Pool

The last question is where is string pool? This is related with the memory structure of JVM and we will just gloss over it.

JVM

As we all know, JVM has some key components: class loading system, runtime, execution engine, etc. The heap in runtime area is the area of program allocation and ‘String Pool’ is no exception.

Heap

Heap is divided into three main areas in Java, according to the age:

  • Young Generation
  • Old Generation, tenured space
  • Permanent Generation – removed in Java8, replaced with meta area

In Java 6 and before, ‘String Pool’ is stored in Permanent Generation, but it is moved to Young/Old Generation (string literal is on Old Generation, but there may exists some string object which is on young generation1) in Java 7 in order to assist the removal of Permanent Generation.

// (1) string const is in String Pool (tenured space)
// (2) new allocated object should normally on young generation
// So: s is on young area not in String Pool, "1" in String Pool (tenured space)
String s = new String("1");

Detailed Explanation

So back to our example, this time we add more explanation comment:

String s1 = new String("s1");
// (1) s1.intern() will return ref to "s1" which is in tenured space
// (2) s1 is on young generation, not in String Pool 
// So: s1 != "s1"
System.out.println(s1.intern() == s1);
String s2 = new String("s") + new String("2");
// (1) s2 is on young area
// (2) String Pool doesn't not have "s2", so s2 is added and returned
// So: s2 == s2
System.out.println(s2.intern() == s2);
Strig s3 = "s3";
// (1) "s3" is in String Pool
// (2) s3.intern try to find same content string and find itself, just return s3
// s3 == s3, "s3" == "s3"
System.out.println(s3.intern() == s3);

More Tests

Write the Output (Environment: Java7)

One

String s1 = new String("1");
s1.intern();
String s2 = "1";
System.out.println(s1 == s2);

String s3 = new String("1") + new String("1");
s3.intern();
String s4 = "11";
System.out.println(s3 == s4);

Second

String s1 = new StringBuilder("why").append("true").toString();
System.out.println(s1.intern() == s1);

Why and When

We talked a lot about String.intern(), but why we need it?

As we have said above, the interned string is in a string pool, which is a cache for unique strings. So the functionality of this method is to save memory when we have many duplicate strings. But be careful about this JVM maintained cache, it can’t be evicted, which may be not suitable for your case.

Actually, Long/Integer/Byte etc also have some object pooling, to save memory, like following:

public static Long valueOf(long l) {  
    final int offset = 128;  
    if (l >= -128 && l <= 127) { // will cache  
        return LongCache.cache\[(int)l + offset\];  
    }  
    return new Long(l);  
}

Ref

Written with StackEdit.


  1. This conclusion is from the this method source (which is called when need to add string to string pool; comments are mine), and may be changed during version. So you should not depend on this behavior: ↩︎

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation

Implement isdigit

It is seems very easy to implement c library function isdigit , but for a library code, performance is very important. So we will try to implement it and make it faster. Function So, first we make it right. int isdigit ( char c) { return c >= '0' && c <= '9' ; } Improvements One – Macro When it comes to performance for c code, macro can always be tried. #define isdigit (c) c >= '0' && c <= '9' Two – Table Upper version use two comparison and one logical operation, but we can do better with more space: # define isdigit(c) table[c] This works and faster, but somewhat wasteful. We need only one bit to represent true or false, but we use a int. So what to do? There are many similar functions like isalpha(), isupper ... in c header file, so we can combine them into one int and get result by table[c]&SOME_BIT , which is what source do. Source code of ctype.h : # define _ISbit(bit) (1 << (