3

Is it safe to perform foreach, add, remove, size operations in different threads with the next set?

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

I.e. 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.

I know that ConcurrentHashMap is thread safe, but I am confused about the thread safety of its Set.

Oleksandr
  • 3,574
  • 8
  • 41
  • 78
  • Possible duplicate of [Is iterating ConcurrentHashMap values thread safe?](https://stackoverflow.com/questions/3768554/is-iterating-concurrenthashmap-values-thread-safe) – Yogesh_D Aug 23 '17 at 11:54
  • 2
    @Yogesh_D it is not a duplicate, He ask about the Set view over concurrentHashMap, which isn't documented well. The comment doc for newKeysSet() is very poor. – Krzysztof Cichocki Aug 23 '17 at 11:58
  • @KrzysztofCichocki "but I need to be sure that there will not be any exceptions while I am doing foreach / add / remove / size operations." because of this. – Yogesh_D Aug 23 '17 at 12:03

2 Answers2

2

Yes, the keySet view is thread safe, the newKeySet in java >=8 is equivalent to this java 7 form:

for java <= 7

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

for java >=8

Set threadSafeSet =  ConcurrentHashMap.newKeySet();
Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
-2

From 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. (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.

Yogesh_D
  • 17,656
  • 10
  • 41
  • 55
  • If you voted to close the question as duplicate why do you answer it? Also you just repeat what I have already answered, and you just copy the documentation... – Krzysztof Cichocki Aug 23 '17 at 12:00