简体   繁体   中英

Is String.intern() thread safe

I would like to use String.intern() in Java to save memory (use the internal pool for strings with the same content). I call this method from different threads. Is it a problem?

The short answer to your question is yes. It's thread-safe.

However, you might want to reconsider using this facility to reduce memory consumption. The reason is that you are unable to remove any entires from the list of interned strings. A better solution would be to create your own facility for this. All you'd need is to store your strings in a HashMap<String,String> like so:

public String getInternedString(String s) {
    synchronized(strings) {
        String found = strings.get(s);
        if(found == null) {
            strings.put(s, s);
            found = s;
        }
        return found;
    }
}
  • As an immutable Java-String is returned, the method is thread-safe. You cannot manipulate the String as-is.

  • The documentation really suggests that it is thread-safe. (by emphasizing for any )

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

  • Thirdly, the JNI-interface uses C-language jobject s. jstring is one of them and is as all jobject s immutable by definition. Thus, also on a native c-level we preserve thread-safety.

Naming these, we have good reasons to say it's thread-safe.

PS: However, you could end up in challenging results if you use multiple class loaders, because the String-pool is maintained per String-class .

A pool of strings, initially empty, is maintained privately by the class String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM