Video in progress

Strong Middle 🧺 Collections

When you need a Set in multithreaded code, what do you take: ConcurrentHashMap.newKeySet(), Collections.newSetFromMap, or something else?

If you don't need ordering, ConcurrentHashMap.newKeySet(): lock-free reads and an atomic add that answers the question "was I the first to add it?". If you need ordering, ConcurrentSkipListSet; for a small set that rarely changes, CopyOnWriteArraySet.

📖 Answer

There is no ConcurrentHashSet class in the JDK, and people often trip on this in interviews. Use this instead:

Set<String> seen = ConcurrentHashMap.newKeySet();

if (seen.add(eventId)) {        // atomic: only one thread gets true for a given eventId
    process(event);
}

Inside add, putIfAbsent runs, so "check and add" is not done as separate steps, and that is exactly what you need for deduplication. If you split contains + add into two calls, two threads will process the same event twice.

Collections.newSetFromMap(map) is a general adapter: it builds a Set out of the keys of the Map you give it. Before Java 8, this is how you got a concurrent set. Today it comes in handy in other cases:

Set<Object> visited = Collections.newSetFromMap(new IdentityHashMap<>());
Set<Listener> weak  = Collections.newSetFromMap(new WeakHashMap<>());

Other options:

  • Collections.synchronizedSet(new HashSet<>()): one lock, and you need a manual synchronized for iteration; there is little reason to choose it in new code;
  • ConcurrentSkipListSet: sorted, O(log n);
  • CopyOnWriteArraySet: a CopyOnWriteArrayList inside, and add is O(n), because it searches for a duplicate linearly and copies the array. Fine for a few dozen listeners, not for thousands of elements.

One detail: the set returned by newKeySet() doesn't accept null, which is a ConcurrentHashMap rule.