Search code examples
javasetjava-8java.util.concurrentconcurrenthashmap

ConcurrentHashMap.newKeySet() vs Collections.newSetFromMap()


Java 8 introduced new way to obtain a concurrent Set implementation

// Pre-Java-8 way to create a concurrent set
Set<String> oldStyle = Collections.newSetFromMap(new ConcurrentHashMap<>());
// New method in Java 8
Set<String> newStyle = ConcurrentHashMap.newKeySet();

Is there any reason to prefer new method?

Any advantages/disadvantages?


Solution

  • ConcurrentHashMap.newKeySet() should be somewhat more efficient as removes a single level of indirection. Collections.newSetFromMap(map) is mostly based on redirecting the operations to the map.keySet(), but ConcurrentHashMap.newKeySet() is very close to map.keySet() itself (just with additions support).

    As for functionality, I see no difference.