Alexandr Alexandr - 1 month ago 12
Java Question

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?

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.

Answer Source

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();