No ConcurrentHashSet? No Problem

2013-03-28 00:51UTC

The JDK provides several concurrent Set classes, each with their own application, but it does not provide a ConcurrentHashSet. Using the Collections utility class, however, such a structure may be created.

If you have ever looked at the source of java.util.HashSet, you will have noticed that it is a simple wrapper around java.util.HashMap. A similar strategy is used by the JDK to create, at runtime, a Set from a backing Map:

final Set<E> concurrentSet = 
    Collections.newSetFromMap(new ConcurrentHashMap<E, Boolean>(...));

The actual contract is defined in the javadocs. Using this method allows you to create, effectively, a ConcurrentHashSet without having to resort to a synchronized set.