Want a ConcurrentHashSet Now?

Home » Want a ConcurrentHashSet Now? » Java » Want a ConcurrentHashSet Now?

Most likely you came here because you know the java.util.concurrent.ConcurrentHashMap class but couldn’t find java.util.concurrent.ConcurrentHashSet. Sorry, this is not in the Java API yet.

The good news is that from Java 6 onwards the Collections API provides a method that allows one to obtain the java.util.Map‘s backing java.util.Set. Here it is: [code]java.util.Collections.newSetFromMap(Map map)[/code], the map passed must be empty.

Let’s say you need a Concurrent HashSet of Strings, just do the following:
[code language=’java’] Set<String> stringSet = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
[/code]

Leave a Comment