Showing posts with label concurrent hashset. Show all posts
Showing posts with label concurrent hashset. Show all posts

Wednesday, 22 June 2011

ConcurrentHashSet in Java from ConcurrentHashMap

While you do have a ConcurrentHashMap class in Java, there is no ConcurrentHashSet.
Solution
You can easily get a ConcurrentHashSet with the following code -

Collections.newSetFromMap(new ConcurrentHashMap<Object,Boolean>())

Notes
  • A Set lends itself to implementation via a Map if you think about it. So can actually just use a Map. But that may not fit in well with the context of your use.
  • The HashSet class internally uses a HashMap.
  • The ConcurrentHashSet obtained via the method inherits pretty much all the concurrency features of the underlying collection.
  • See api-docs for newSetFromMap