简体   繁体   English

String.intern()线程是否安全

[英]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). 我想在Java中使用String.intern()来节省内存(使用内部池来获取具有相同内容的字符串)。 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. 原因是您无法从实习字符串列表中删除任何entires。 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: 您只需将字符串存储在HashMap<String,String>如下所示:

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. 返回不可变的Java-String时,该方法是线程安全的。 You cannot manipulate the String as-is. 您无法按原样操纵String。

  • 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. 因此, 对于任何两个字符串s和t,当且仅当s.equals(t)为真时,s.intern()== t.intern()才为真。

  • Thirdly, the JNI-interface uses C-language jobject s. 第三,JNI接口采用C语言jobject秒。 jstring is one of them and is as all jobject s immutable by definition. jstring是其中之一,并且根据定义,所有jobject都是不可变的。 Thus, also on a native c-level we preserve thread-safety. 因此,在本机c级别上,我们也保留了线程安全性。

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 . PS:但是,如果使用多个类加载器,最终可能会遇到挑战性的结果,因为String-pool是按String-class维护的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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