是否循环ConcurrentHashMap值线程安全? [英] Is iterating ConcurrentHashMap values thread safe?

查看:279
本文介绍了是否循环ConcurrentHashMap值线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javadoc中, ConcurrentHashMap 是以下内容:

In javadoc for ConcurrentHashMap is the following:


检索操作(包括get)一般不会阻塞,因此可能与更新操作去掉)。检索反映了最新完成的更新操作的结果。对于诸如putAll和clear的聚合操作,并发检索可以反映仅插入或去除一些条目。类似地,迭代器和枚举返回反映在迭代器/枚举创建时或自从创建迭代器/枚举的某点处的散列表的状态的元素。它们不会抛出ConcurrentModificationException。 但是,迭代器设计为一次只能使用一个线程。

?如果我尝试用两个线程同时迭代地图会发生什么?如果我在迭代时从地图中移除或移除值,会发生什么?

What does it mean? What happens if I try to iterate the map with two threads at the same time? What happens if I put or remove a value from the map while iterating it?

推荐答案


这意味着?

What does it mean?

这意味着从 ConcurrentHashMap 获得的每个迭代器设计为由单个线程使用并且不应该传递。这包括了for-each循环提供的语法糖。

That means that each iterator you obtain from a ConcurrentHashMap is designed to be used by a single thread and should not be passed around. This includes the syntactic sugar that the for-each loop provides.


如果我尝试使用两个线程迭代映射,会发生什么时间?

What happens if I try to iterate the map with two threads at the same time?

如果每个线程都使用自己的迭代器,它会正常工作。

It will work as expected if each of the threads uses it's own iterator.


如果在迭代时从地图中移除或移除值,会发生什么?

What happens if I put or remove a value from the map while iterating it?

如果你这样做,就可以保证事情不会中断(这是 ConcurrentHashMap 意味着并发的一部分)。然而,不能保证一个线程将看到另一个线程执行的映射的改变(没有从映射获得新的迭代器)。迭代器保证在映射创建时反映映射的状态。

It is guaranteed that things will not break if you do this (that's part of what the "concurrent" in ConcurrentHashMap means). However, there is no guarantee that one thread will see the changes to the map that the other thread performs (without obtaining a new iterator from the map). The iterator is guaranteed to reflect the state of the map at the time of it's creation. Futher changes may be reflected in the iterator, but they do not have to be.

总之,像

for (Object o : someConcurrentHashMap.entrySet()) {
    // ...
}

几乎每次看到它都会很好(或至少安全)。

will be fine (or at least safe) almost every time you see it.

这篇关于是否循环ConcurrentHashMap值线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆