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();