This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: Why is there no ConcurrentHashSet for ConcurrentHashMap?

As you know, a HashSet is based on a HashMap.

If we look at the HashSet implementation, we see that everything is managed by HashMap<E,Object>.

At the same time, we know that this HashMap is not thread-safe. That’s why we use Java’s ConcurrentHashMap. (Hashtable, of course.)

Based on the above two conditions, I am confused why we don’t have ConcurrentHashSet based on ConcurrentHashMap.

Did I miss something vital? I need Set to work in a multithreaded environment.

Also, if I want to create a HashSet that supports multiple threads myself, can ConcurrentHashSet be implemented by replacing only the HashMap with ConcurrentHashMap and keeping the rest of the code consistent with the HashSet?

Answer 1: There is no built-in ConcurrentHashMap in Java, because you can always generate a set by using a map. There are many kinds of maps, so you can also generate many sets (including ConcurrenthashSets) from maps.

Prior to Java 8, you could generate a HashSet that supported concurrency in the following way

Collections.newSetFromMap(map)
Copy the code

After Java 8, you can get a “ConcurrentHashSet” directly from a ConcurrentHashMap,

HashSet set = ConcurrentHashMap. NewKeySet ();Copy the code

This approach is much simpler than the previous one, which requires us to generate a map, possibly even an empty map that exists only to create a HashSet that supports multiple threads, which is a waste of resources.

Note that:

The Collections. Create a SetFromMap newSetFromMap. The setFrommap. removeAll method delegates to keysetView.removeall, which is extremely inefficient at removing a large number of elements, so the first method is not recommended.