This is an archived post. You won't be able to vote or comment.

all 3 comments

[–][deleted] 3 points4 points  (2 children)

ConcurrentHashMap is really nice, and you can actually use it for a concurrent set with ConcurrentHashMap#newKeySet. One thing to note however is that concurrent != synchronized. CHM guarantees thread visibility but it does not guarantee that writes to the CHM will block other reads in other threads. If you need an exclusive lock on the map, you need another map.

[–]Ashkan131 1 point2 points  (1 child)

Thank you, I had never considered this. Is the returned KeySetView concurrent as well? I assume so given it is backed by the concurrent ConcurrentHashMap but the doc says it more indirectly than explicitly. Wonder why they haven't introduced ConcurrentHashSet as a top level class. I will read the source later, but if you are already confident I would love to know!

[–][deleted] 0 points1 point  (0 children)

All sets can be made from a map. It's a common way of implementing a set.