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

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    ReplyDelete