问题描述
我想在Java中使用String.intern()来节省内存(使用内部池来获取具有相同内容的字符串)。我从不同的线程调用此方法。这是一个问题吗?
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.
但是,您可能想重新考虑使用此工具来减少内存消耗。原因是您无法从实习字符串列表中删除任何entires。更好的解决方案是为此创建自己的设施。您所需要的只是将字符串存储在 HashMap< String,String>
中,如下所示:
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;
}
}
这篇关于String.intern()线程是否安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!