java 何时使用 ConcurrentHashMap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14228974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:31:59  来源:igfitidea点击:

When to use ConcurrentHashMap

javaconcurrent-collections

提问by mehta

Possible Duplicate:
What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

可能的重复:
ConcurrentHashMap 和 Collections.synchronizedMap(Map) 之间有什么区别?

I was reading differences between HashMap, Collenctions.synchonizedMap and ConcurrentHashMap. My understanding is that Collections.synchronizedMap applied lock on entire collection, hence performance overhead. But ConcurrentHashMap doesn't use synchronization. It uses segments to achieve the results, so it offers a similar performance as that of HashMap.

我正在阅读 HashMap、Collections.synchronizedMap 和 ConcurrentHashMap 之间的差异。我的理解是 Collections.synchronizedMap 对整个集合应用了锁,因此性能开销。但是 ConcurrentHashMap 不使用同步。它使用段来实现结果,因此它提供了与 HashMap 相似的性能。

Please suggest if my understanding is correct. Also if this is the case, can I use ConcurrentHashMap everywhere even if there may not be multiple threads accessing it?

请建议我的理解是否正确。此外,如果是这种情况,即使可能没有多个线程访问它,我是否可以在任何地方使用 ConcurrentHashMap?

回答by Scorpion

ConcurrentHashMap doesn't use synchronization. It uses segments to achieve the results

ConcurrentHashMap 不使用同步。它使用段来实现结果

ConcurrentHashMap synchronizes at the segment level allowing atomic operation like putIfAbsent or replace old value with new value. The advantage is derived by a technique called lock-striping.

ConcurrentHashMap 在段级别同步,允许像 putIfAbsent 这样的原子操作或用新值替换旧值。这种优势来自一种称为锁条的技术。

can I use ConcurrentHashMap everywhere even if there may not be multiple threads accessing it?

即使可能没有多个线程访问它,我可以在任何地方使用 ConcurrentHashMap 吗?

No, there's no reason that I can think of for doing that. Leaving performance apart, the choice of a data structure also serves as a documentation as to how the code is expected to be used (HashMap--> single thread). Use ConcurrentHashMap only when the class where it's being used is thread safe; otherwise the use of a thread safe data structure in a non thread safe class adds to the confusion of the next person looking at the code.

不,我想不出这样做的理由。撇开性能不谈,数据结构的选择也可作为有关如何使用代码的文档(HashMap--> 单线程)。仅当使用 ConcurrentHashMap 的类是线程安全的时才使用它;否则,在非线程安全类中使用线程安全数据结构会增加下一个查看代码的人的困惑。