简体   繁体   English

ConcurrentHashMap的集合在foreach中是否是线程安全的?

[英]Does Set of ConcurrentHashMap is thread safe in foreach?

Is it safe to perform foreach, add, remove, size operations in different threads with the next set? 在下一组中执行foreach,添加,删除,调整不同线程中的操作是否安全?

private final Set<MyObject>  myConcurrentHashSet = ConcurrentHashMap.newKeySet();

Ie I don't need to get maximum accuracy in foreach or size operations but I need to be sure that there will not be any exceptions while I am doing foreach / add / remove / size operations. 即我不需要在foreach或size操作中获得最大的准确性,但我需要确保在进行foreach / add / remove / size操作时不会有任何异常。

I know that ConcurrentHashMap is thread safe, but I am confused about the thread safety of its Set. 我知道ConcurrentHashMap是线程安全的,但我对它的Set的线程安全感到困惑。

Yes, the keySet view is thread safe, the newKeySet in java >=8 is equivalent to this java 7 form: 是的,keySet视图是线程安全的,java> = 8中的newKeySet相当于这个java 7形式:

for java <= 7 for java <= 7

ConcurrentHashMap c = ...;
Set threadSafeSet = c.keySet();

for java >=8 对于java> = 8

Set threadSafeSet =  ConcurrentHashMap.newKeySet();

From ConcurrentHashMap documentation: 来自ConcurrentHashMap文档:

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). 检索操作(包括get)通常不会阻塞,因此可能与更新操作(包括put和remove)重叠。 Retrievals reflect the results of the most recently completed update operations holding upon their onset. 检索反映了最近完成的更新操作的结果。 (More formally, an update operation for a given key bears a happens-before relation with any (non-null) retrieval for that key reporting the updated value.) (更正式地说,给定密钥的更新操作承担与该密钥报告更新值的任何(非空)检索之前发生的关系。)
. .

Similarly,Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. 类似地,Iterators,Spliterators和Enumerations在迭代器/枚举的创建时或之后的某个时刻返回反映哈希表状态的元素。 They do not throw ConcurrentModificationException. 它们不会抛出ConcurrentModificationException。 However, iterators are designed to be used by only one thread at a time. 但是,迭代器设计为一次只能由一个线程使用。

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

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