Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to create a thread-safe ConcurrentHashSet in Java 8?

Until JDK 8, there was no way to create a large, thread-safe, Concurrenthashset in Java. The java.util.concurrent package doesn't even have a class called ConcurrentHashSet, but from JDK 8 onwards, you can use newly added keySet(default value) and newKeySet() method to create a ConcurrentHashSet backed by ConcurrentHashMap. Unlike tactical solutions like using concurrent hash map with dummy value or using the set view of the map, where you cannot add new elements. The Set returned by keySet(defaultValue) and newKeySet() method of JDK 8 is a proper set, where you can also add new elements along with performing other set operations e.g. contains(), remove() etc. Though you need to be careful that these methods are only available in ConcurrentHashMap class and not in ConcurrentMap interface, so you need to use a ConcurrentHashMap variable to hold the reference, or you need to use type casting to cast a ConcurrentHashMap object stored in ConcurrentMAp variable.
Read more »


This post first appeared on Javarevisited: Blog About Java Programmin, please read the originial post: here

Share the post

How to create a thread-safe ConcurrentHashSet in Java 8?

×

Subscribe to Javarevisited: Blog About Java Programmin

Get updates delivered right to your inbox!

Thank you for your subscription

×