Creating a concurrent Set in Java

Steve Neal Uncategorized Leave a Comment

The concurrent collections are a great help for multi-threaded programming in Java, but there is no concurrent Set class provided in the API.

The trick is to use the key set of a ConcurrentHashMap, wrapped by the Set interface. The Collections class provides a static method which will do this for you:

Set<String> names 
    = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());

Just pass an instance of a ConcurrentHashMap (of the appropriate type) to this method and it will wrap it with a Set class that delegates calls to the underlying map, using it’s keys as the concurrent set.

Simple eh?

Leave a Reply

Your email address will not be published. Required fields are marked *