[SOLVED] How to create ConcurrentHashSet before and after Java 8

[SOLVED] How to create ConcurrentHashSet before and after Java 8

There are at least two ways to create ConcurrentHashSet in Java. One of them works in Java 8 or newer. The second one works well in older versions of Java.

You want to create ConcurrentHashSet but it is missing in the java.util.concurrent package. As an explanation – the package contains some concurrent implementations of collection and map interfaces.


The implementation of ConcurrentHashSet is missing because you can always get it from ConcurrentHashMap or just use a special implementation of SortedSet called ConcurrentSkipListSet.


Solution A: ConcurrentHashSet derived from ConcurrentHashMap (Java 8 or newer)
If you use at leat Java 8 in your project, this is recommended solution for the problem of missing  ConcurrentHashSet class.

Set<String> myConcurrentSet = ConcurrentHashMap.newKeySet();


Solution B: ConcurrentHashSet derived from ConcurrentHashMap
If you use an older Java version you can retrieve ConcurrentHashSet from dummy ConcurrentHashMap instance.

Map<String, String> myMap = new ConcurrentHashMap<String, String>();
Set<String> myConcurrentSet = Collections.newSetFromMap(myMap);


Solution C: Use ConcurrentSkipListSet
If you need a sorted set implementaion or you don’t care about momory overhead, you can always use ConcurrentSkipListSet implementation from the java.util.concurrent package.

Set<String> myConcurrentSet = new ConcurrentSkipListSet<>(String);

0 0 vote
Article Rating
Notify of
Inline Feedbacks
View all comments