Is String.intern() thread safe

前端 未结 2 1969

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?

2条回答
  •  囚心锁ツ
    2021-02-13 09:55

    • 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.
    

提交回复
热议问题