I wonder if it is thread-safe to use a concurrent HashSet
in Java in which concurrent writes from more than 1 threads can occur if we can guarantee that each thread can add()/remove() only a unique value
for example, a thread can add()/remove() to/from a the HashSet
its own id)
I have read that in any case when there are concurrent writes in a HashSet
, it is not thread-safe but I do not understand why is that true in my previous example. Since each thread can add()/remove() only a unique value (like threadID) which is not going to be added or removed from another thread and as a result there are no dependencies between the threads insertions and deletions, why is not that thread-safe?
Finally, is there any more intelligent way to implement this instead of creating a ConcurrentHashMap
which contains keys with empty values?
EDIT: I have read this post but my question still is not answered. I do not understand why the HashSet
can be affected by concurrent writes of different values.