Why there is no ConcurrentHashSet against ConcurrentHashMap
Solution 1
There's no built in type for ConcurrentHashSet
because you can always derive a set from a map. Since there are many types of maps, you use a method to produce a set from a given map (or map class).
Prior to Java 8, you produce a concurrent hash set backed by a concurrent hash map, by using Collections.newSetFromMap(map)
In Java 8 (pointed out by @Matt), you can get a concurrent hash set view via ConcurrentHashMap.newKeySet()
. This is a bit simpler than the old newSetFromMap
which required you to pass in an empty map object. But it is specific to ConcurrentHashMap
.
Anyway, the Java designers could have created a new set interface every time a new map interface was created, but that pattern would be impossible to enforce when third parties create their own maps. It is better to have the static methods that derive new sets; that approach always works, even when you create your own map implementations.
Solution 2
Set<String> mySet = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
Solution 3
With Guava 15 you can also simply use:
Set s = Sets.newConcurrentHashSet();
Solution 4
Like Ray Toal mentioned it is as easy as:
Set<String> myConcurrentSet = ConcurrentHashMap.newKeySet();
Solution 5
It looks like Java provides a concurrent Set implementation with its ConcurrentSkipListSet. A SkipList Set is just a special kind of set implementation. It still implements the Serializable, Cloneable, Iterable, Collection, NavigableSet, Set, SortedSet interfaces. This might work for you if you only need the Set interface.
Talha Ahmed Khan
Updated on October 08, 2020Comments
-
Talha Ahmed Khan over 3 years
HashSet is based on HashMap.
If we look at
HashSet<E>
implementation, everything is been managed underHashMap<E,Object>
.<E>
is used as a key ofHashMap
.And we know that
HashMap
is not thread safe. That is why we haveConcurrentHashMap
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 theHashMap
toConcurrentHashMap
and leaving the rest as is?