Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 857
ranr Avatar asked Feb 10 '13 13:02

ranr


People also ask

Is string intern thread-safe?

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

What does string intern () method do?

The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool. Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.

What is String intern () When and why should it be used?

String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. By applying String. intern() on a couple of strings will ensure that all strings having the same contents share the same memory.

Does Java automatically intern strings?

intern() in Java. All compile-time constant strings in Java are automatically interned using this method. String interning is supported by some modern object-oriented programming languages, including Java, Python, PHP (since 5.4), Lua,Julia and .


2 Answers

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;
    }
}
like image 135
Elias Mårtenson Avatar answered Oct 10 '22 04:10

Elias Mårtenson


  • 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 jobjects. jstring is one of them and is as all jobjects 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.
like image 35
poitroae Avatar answered Oct 10 '22 02:10

poitroae