Concurrent Sets
Java does not have a “ConcurrentHashSet” as a top-level class. Instead, it provides sets based on its existing concurrent map and list implementations.
ConcurrentSkipListSet #
ConcurrentSkipListSet is a thread-safe implementation of NavigableSet backed by a ConcurrentSkipListMap. It is sorted and lock-free.
Canonical Usage: Use ConcurrentSkipListSet when you need a sorted set that can be accessed by many threads concurrently, especially for range queries (e.g., all elements between “B” and “F”).
NavigableSet<String> set = new ConcurrentSkipListSet<>();
set.addAll(Arrays.asList("C", "A", "B"));
set.first(); // Returns "A"
set.subSet("A", "C"); // Returns ["A", "B"]
CopyOnWriteArraySet #
CopyOnWriteArraySet is a Set that uses an internal CopyOnWriteArrayList for all of its operations. It has the same copy-on-write properties as the list it is based on.
Canonical Usage: Use CopyOnWriteArraySet for collections of unique listeners or small sets of configuration items that are updated infrequently but read often.
private final Set<Listener> listeners = new CopyOnWriteArraySet<>();
// Adding is slow (O(n) copy + O(n) scan), but notification is fast and wait-free!
public void fire(Event e) {
for (Listener l : listeners) l.onEvent(e);
}