gpt4 book ai didi

java - ConcurrentHashMap中 'thread-safe'的含义

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:57:10 24 4
gpt4 key购买 nike

由于桶级锁定,当使用 CHM 代替 Collections.synchronizedMap(...)/hashtable 时可以提供性能提升。

当我们不希望我们的迭代器抛出 ConcurrentModificationException 时,我们也可以使用 CHM。

但我对 CHM 上下文中 thread-safe 的含义感到困惑,因为它们不会阻止更改在检索和写入重叠之间得到反射(reflect)?

最佳答案

线程安全意味着您可以在多个线程之间共享一个ConcurrentHashMap 对象,并且可以在没有外部锁定的情况下并发访问/修改该对象。

确切的语义在 documentation 中有解释。 :

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset.

For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.

关于java - ConcurrentHashMap中 'thread-safe'的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11015694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com