2017  Kodetalk | Feedback | Privacy Policy | Terms | About

Why there is no ConcurrentHashSet against ConcurrentHashMap

HashSet is based on HashMap.

If we look at HashSet<E> implementation, everything is been managed under HashMap<E,Object>.

<E> is used as a key of HashMap.

And we know that HashMap is not thread safe. That is why we have ConcurrentHashMap in Java.

Based on this, I am confused that why we don"t have a ConcurrentHashSet which should be based on the ConcurrentHashMap?

Is there anything else that I am missing? I need to use Set in a multi-threaded environment.

Also, If I want to create my own ConcurrentHashSet can I achieve it by just replacing the HashMap to ConcurrentHashMap and leaving the rest as is?


You can trivially produce a concurrent hash set backed by a concurrent hash map, by using newSetFromMap, explained in detail at http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#newSetFromMap(java.util.Map)

I suspect the designers of the API felt that providing a (static) method to produce a set based on any map was better than creating a new set interface every time a new map interface was added. That said, it does feel somewhat clunky that you have to create an empty map to pass to this method, doesn't it?


With Guava 15 you can also simply use:

Set s = Sets.newConcurrentHashSet();
Answer is