1

I have a data structure like this in java:

ConcurrentHashMap<String, Set<String>> objects; 

Set(HashSet) is not a concurrent data structure.

Multiple threads can safely mutate the ConcurrentHashMap but what about the Set in it? Is the Set objects in the Map are thread-safe? Or the ConcurrentHashMap provides thread-safety for itself only?

Thanks

xyzt
  • 1,201
  • 4
  • 18
  • 44
  • Yes. the keySet and entrySet is thread-safe. Good to read. https://stackoverflow.com/questions/3768554/is-iterating-concurrenthashmap-values-thread-safe – Mebin Joe Apr 10 '19 at 10:31
  • Thread-safety usually implies maintaining a state in consistent state under conditions of concurrent access.`ConcurrentHashMap` guarantees only thread safety of its own state against, inserting, removing, lookup, etc. operations made on it. The containerized objects should provide the thread safety of their state (which is unknown for the `ConcurrentHashMap`) by themselves. – Dmytro Mukalov Apr 10 '19 at 10:48

1 Answers1

0

Set object in the Map is not thread safe. The Map does not make it thread safe only because it contains a reference to the set.

ConcurrentHashMap implementation provides thread safety only for its own operations, such as putting, retrieval, removal, content checks, etc.

If so happens that the same Set is modified simultaneously by several threads, the result of these modifications is unpredictable.

If you need synchronization of the Set object, you may consider using a Set wrapper for ConcurrentHashMap:

Set<String> set = ConcurrentHashMap.newKeySet();

or, simply:

Set<String> set = ...;
set = Collections.synchronizedSet(set);
Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28