简体   繁体   English

“ConcurrentHashMap.putAll(...)”是原子的吗?

[英]Is “ConcurrentHashMap.putAll(…)” atomic?

Is the method ConcurrentHashMap.putAll(Map) supposed to be atomic? 方法ConcurrentHashMap.putAll(Map)应该是原子的吗?

I cannot find it in the documentation and it is not mentioned in the ConcurrentMap interface, so I guess the answer is no. 我在文档中找不到它,并且在ConcurrentMap界面中没有提到它,所以我猜答案是否定的。 I am asking it to be sure, since it wouldn't make sense if that operation wasn't atomic to be honest. 我要求它确定,因为如果该操作不是原子的,那就没有意义。

If it isn't atomic, what would be the best way to support atomic inserts of multiple items? 如果它不是原子的,那么支持多个项目的原子插入的最佳方法是什么? Back to the good old synchronized? 回到好老同步?

It's not atomic, no. 这不是原子的,不是。 According to the class documentation : 根据课程文件

For aggregate operations such as putAll and clear , concurrent retrievals may reflect insertion or removal of only some entries. 对于诸如putAllclear类的聚合操作,并发检索可能反映仅插入或删除某些条目。

To atomicize it, you'll have to use synchronized , yes. 要使其原子化,你必须使用synchronized ,yes。 There's no non-blocking way to do this. 没有非阻塞的方法来做到这一点。

at the top of the doc 文档的顶部

For aggregate operations such as putAll and clear , concurrent retrievals may reflect insertion or removal of only some entries. 对于诸如putAllclear类的聚合操作,并发检索可能反映仅插入或删除某些条目。

To atomicize it, you'll have to use synchronized, yes 要使其原子化,你必须使用synchronized,yes

Not only that: you have to put a synchronized block around every public map method thus degrading concurrency. 不仅如此:您必须在每个公共映射方法周围放置一个synchronized块,从而降低并发性。

putAll()不是原子的,而只是保证每个put()都是原子的。

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

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