ConcurrentHashMap 的 Set 在 foreach 中是线程安全的吗?
Does Set of ConcurrentHashMap is thread safe in foreach?
下一组在不同线程中执行foreach、add、remove、size操作是否安全?
private final Set<MyObject> myConcurrentHashSet = ConcurrentHashMap.newKeySet();
即我不需要在 foreach 或 size 操作中获得最大的准确性,但我需要确保在执行 foreach / add / remove / size 操作时不会有任何异常。
我知道ConcurrentHashMap是线程安全的,但是我对它的Set的线程安全很疑惑
是的,keySet视图是线程安全的,java>=8中的newKeySet相当于这个java7形式:
对于 java <= 7
ConcurrentHashMap c = ...;
Set threadSafeSet = c.keySet();
对于 java >=8
Set threadSafeSet = ConcurrentHashMap.newKeySet();
来自 ConcurrentHashMap 文档:
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. (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. They do not throw
ConcurrentModificationException. However, iterators are designed to be
used by only one thread at a time.
下一组在不同线程中执行foreach、add、remove、size操作是否安全?
private final Set<MyObject> myConcurrentHashSet = ConcurrentHashMap.newKeySet();
即我不需要在 foreach 或 size 操作中获得最大的准确性,但我需要确保在执行 foreach / add / remove / size 操作时不会有任何异常。
我知道ConcurrentHashMap是线程安全的,但是我对它的Set的线程安全很疑惑
是的,keySet视图是线程安全的,java>=8中的newKeySet相当于这个java7形式:
对于 java <= 7
ConcurrentHashMap c = ...;
Set threadSafeSet = c.keySet();
对于 java >=8
Set threadSafeSet = ConcurrentHashMap.newKeySet();
来自 ConcurrentHashMap 文档:
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. (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. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.