Lesson · Concurrent Collections
ConcurrentSkipListSet: the sorted Set view
14 min readConcurrentSkipListSet
ConcurrentSkipListSet is a thin Set view over ConcurrentSkipListMap: every element is a key, and every key shares one dummy value. That single fact explains all of its behaviour, from expected O(log n) add and contains to the navigable quartet, the subsets that are views, and the nulls that throw instead of answering false.
Order, or concurrency: pick two?
A shared set of active session IDs is easy: take a concurrent set and move on. The harder version of the same requirement adds one word. Which session expires first? Which sessions expire in the next minute? An unordered concurrent set cannot answer either question, because it holds no order.
The sorted Set in the library is TreeSet, and it has no concurrent sibling. Sharing one means locking every read, which is the combination the sorted map lesson already priced out. The library answer is ConcurrentSkipListSet: a concurrent, sorted, navigable Set that is built on the skip-list map, so the guarantees arrive unchanged.
- Expected O(log n) for add, contains and remove, with no lock in the read path.
- Ascending iteration by default, and the full navigable surface: lower, floor, ceiling, higher, subSet, headSet, tailSet.
- Weakly consistent iterators: never a ConcurrentModificationException, never a snapshot either.
- No nulls, and no duplicates by comparison: uniqueness is decided the same way TreeSet decides it.
Sorted and concurrent is the whole point. The class buys the ordering with a log factor instead of a lock, which is the only reason it exists next to ConcurrentHashMap's key set.
What the set inherits from the map
The class description says it in one line: a scalable concurrent NavigableSet based on a ConcurrentSkipListMap. The set itself holds almost no logic. Every operation is a delegation, and every guarantee is borrowed.
That is good news, because it means the interesting questions about this set were already answered in the map lesson: how searches stay lock-free, why the worst case is probabilistic, what weakly consistent means, and why null values are refused. Here, read the same facts through a Set API.
| Set call | What the map does | What you get |
|---|---|---|
| add(e) | putIfAbsent(e, TRUE) | true only for the thread that inserted; expected O(log n), and false when the comparison says it is already there |
| contains(o) | containsKey(o) | expected O(log n), computed by walking the lanes rather than hashing |
| remove(o) | remove(o, TRUE) | a conditional remove that also checks the dummy value; expected O(log n) |
| iterator() | navigableKeySet().iterator() | ascending key order, weakly consistent |
| lower / floor / ceiling / higher | lowerKey / floorKey / ceilingKey / higherKey | the navigable quartet, all expected O(log n) |
| subSet / headSet / tailSet | subMap / headMap / tailMap | a view over the same map, not a copy |
| pollFirst / pollLast | pollFirstEntry / pollLastEntry | one atomic removal of an end, null when the set is empty |
The set is a costume, and the costume is thin. The ordering, the complexity, the weak consistency and the refusals all come from the map. Learn ConcurrentSkipListMap once and this class costs you nothing extra.
ConcurrentSkipListSet lab
add keys, then query the live setUnder the hood: every element is a key mapped to one shared Boolean.TRUE, and the lanes sort them.
Neighbour lookups answer null on an empty set, and a range view is simply empty. Add a key or two and query again.
The same click pattern answers differently in each implementation: one keeps the keys sorted at expected O(log n), the other keeps them unordered at expected O(1) and refuses the range questions.
The dummy value is load-bearing
Inside the set there is one field: a ConcurrentNavigableMap of elements to Object. Every element is stored as a key, and every key is mapped to the same shared instance of Boolean.TRUE. The values carry no information whatsoever, and the set never exposes the map they live in.
That is not an implementation accident, it is what makes the set operations atomic. add(e) is putIfAbsent(e, TRUE) == null, so exactly one thread can see the null and report true, even when several threads add the same element at the same moment. remove(o) is remove(o, TRUE), the conditional form: it removes the mapping only if the value is still the shared dummy. The class comment notes the map field is final for the sake of thread safety, which is the same idea seen from the other side.
The shared value also explains the memory story: a set of a million elements is a map of a million entries pointing at one object, so the per-element cost is the node, not a value object of its own.
- add is putIfAbsent, so at most one caller wins. The boolean result is the map's null check, not a separate lock.
- remove is conditional on the dummy. Passing the shared value means the removal cannot collide with a mapping that was replaced by something else in the meantime.
- contains is containsKey, so it never materialises a value and never touches the dummy.
One shared value turns three Set operations into three atomic map operations. No part of the set needs its own synchronisation, which is why the class is a few hundred lines and not a data structure of its own.
ConcurrentSkipListSet · delegation
one map, one shared valuethree Set calls, three map calls
add("delta")
delegates to
putIfAbsent("delta", TRUE) == null
true only for the caller that inserted; a second add sees the existing key and returns false.
contains("delta")
delegates to
containsKey("delta")
a key check, so the shared value is never even read. A null argument throws here.
remove("delta")
delegates to
remove("delta", TRUE)
conditional: it removes the mapping only if the value is still the shared dummy.
the map underneath
Keys are sorted by the comparison, so iteration walks this lane in order while other threads link and unlink around it. The values never vary, which is why the set can remove conditionally and never needs to read one.
everything else is a delegation too
The set never exposes the map, so the shared value stays invisible. That is the whole class: a NavigableSet contract on top of a concurrent sorted map.
Order decides identity, so respect the order
A Set normally answers identity with equals. This one answers with the comparison, exactly like TreeSet: the element that arrived first is the element that stays, and the second is the one that disappears. Everything else in the lesson follows from that one substitution.
The comparison is chosen at construction: natural ordering by default, or the Comparator you pass in. Every add, contains, remove, subset and iteration resolves through it, so nothing that the comparison reads may change while the set is in use. That rule is where mutable keys and mutable comparators earn their reputation.
- Two records that compare equal are one element. The second add returns false and the object is dropped, however different equals says they are. This is the trap in the callout below, and it is silent.
- An order that disagrees with equals breaks lookups. If equal objects can compare unequal, the set can hold what equals calls duplicates, and a lookup with an equal instance can miss the entry that is there.
- Nulls throw rather than answer. add(null), contains(null) and remove(null) all throw NullPointerException, because the map underneath refuses null keys. HashSet.contains(null) returns false; this class throws, and so does a naturally-ordered TreeSet.
- Wrong types throw too. A set of Strings asked to contains(42) throws ClassCastException when the comparison runs, exactly like TreeMap.
- No positioning calls. addFirst and addLast throw UnsupportedOperationException: position is whatever the comparison says, and nothing else may claim otherwise.
Identity is the comparison, not your equals. Design the element so that two records which must coexist never compare equal, and the set and the map under it will both agree with you.
Iteration, size and bulk operations
iterator() walks ascending key order and is weakly consistent: no ConcurrentModificationException, and no promise to see anything added after it was created. descendingSet and descendingIterator give the other direction, and the class notes that descending views and iterators are slower than ascending ones.
size() carries the best footnote in the class. The Javadoc still warns that size is not a constant-time operation and can be inaccurate, wording inherited from an older implementation that counted by traversal; today the call delegates to the map, which keeps a running count. The number is still a snapshot at some instant, so it cannot hold an invariant on a set that other threads are editing. The Javadoc's closing advice has aged well: the method is typically not very useful in concurrent applications.
Bulk operations are not atomic. addAll, removeIf and forEach can be observed halfway through by a concurrent traversal, so each individual add is atomic and a collection of them is not.
- Subsets are views. subSet, headSet and tailSet wrap the map's range views: removals through them edit the original set, and adding outside the range throws IllegalArgumentException.
- pollFirst and pollLast are single atomic steps that return null when the set is empty. That is the shape of an expiry worker: take the earliest, or stop.
- Spliterators report CONCURRENT, NONNULL, DISTINCT, SORTED and ORDERED, which tells a stream pipeline that the traversal is ordered by key and safe to run alongside writers.
- equals works across Set implementations, because it compares membership both ways rather than relying on a shared type.
Iterate freely, count carefully. The iterator is safe by construction and the count is a moment in time, so any guard of the form if (size() < limit) add(e) is a race rather than a check.
Do you actually need a sorted concurrent set?
Sorted concurrent sets are rare, and knowing when they are not the answer is the more valuable half of this lesson. Sorted output, an ordered index, an expiry queue and range membership are the cases that justify the log factor. Shared membership, deduplication and lock-key sets are not.
| Set | Order | add, contains, remove | Use it when |
|---|---|---|---|
| ConcurrentSkipListSet | ascending by comparison, navigable | expected O(log n) | a caller needs neighbours, ranges, ordered iteration, or an atomic pop of the smallest element |
| ConcurrentHashMap.newKeySet() | none; iteration order is unspecified | expected O(1) | the common case: shared membership, deduplication, seen-keys, no ordering requirement at all |
| CopyOnWriteArraySet | insertion order via a copied array | reads cheap, writes copy the whole array | tiny, read-mostly sets, where iteration must never fight a writer |
| Collections.synchronizedSet(new TreeSet<>()) | ascending by comparison | every call takes the set-wide monitor | a hard worst case matters more than concurrency, and you accept serialization openly |
- Order has to be wanted. If no caller asks for a neighbour or a range, the sorted set is a slower unordered set with extra rules attached.
- Ranges are the differentiator: subSet, ceiling and floor are the calls the hash-based sets cannot answer at all.
- Tiny and read-mostly is a different tool, not a slower version of this one: copying on write is excellent at ten elements and unusable at ten million.
Order costs a log factor; pay it only when you query ranges. Otherwise ConcurrentHashMap.newKeySet() gives you the same concurrency with a better constant factor and no ordering contract to keep.
The decision walk-through
From requirement to implementation, in order:
- Name the operation the unordered set cannot perform: first element, next expiry, everything inside a window. If there is none, use ConcurrentHashMap.newKeySet().
- Check that the element type has one total order, or hand a Comparator to the constructor and use it everywhere the set is read.
- Verify that the order is consistent with equals, or the set will keep what equals calls duplicates and miss lookups for entries it holds.
- Decide the null policy explicitly: this class throws on null instead of answering false, so filter before the call.
- Use the navigable surface instead of scanning. ceiling, floor and subSet are what the log factor pays for.
- Treat size as an observation, never as a guard, and remember that addAll is a loop of atomic adds rather than one batch.
A sorted concurrent set is a map wearing a Set costume. Keep the costume's rules in mind: compare decides identity, nulls are refused, subsets are views, and the map underneath is doing all of the work.
Two records that compare equal are one element
This set decides identity with compareTo, or with the Comparator it was built with, never with equals. Add two objects whose comparison returns zero and the second add returns false: nothing is inserted, nothing is logged, and the data is quietly gone. A leaderboard keyed by score keeps one player per score; an index keyed by a coarse timestamp loses entries that share it. Make the key composite (score plus id, timestamp plus sequence) so that distinct records never compare equal. It is the same rule TreeSet lives by, and the Comparable vs Comparator lesson covers the general contract; in a concurrent structure it bites harder, because the loss is silent and easy to blame on threading.
Interview angles
What is a ConcurrentSkipListSet, structurally?+
A thin wrapper over ConcurrentSkipListMap: a final map field of elements to Object, where every element is a key mapped to one shared Boolean.TRUE. add is putIfAbsent, remove is a conditional remove against that shared value, and contains is containsKey.
The map owns the concurrency and the ordering, and the set adds only the Set contract: uniqueness by comparison, Set equality that works across implementations, and the navigable methods that simply delegate. The class comment notes the field is final for thread safety, which is why the clone method looks slightly awkward.
Common misconception: That the set is a data structure of its own. It is a view, and every guarantee is borrowed from the map.
Follow-up: So when do you choose it over ConcurrentHashMap.newKeySet()?
ConcurrentSkipListSet or ConcurrentHashMap.newKeySet()?+
Order decides it. newKeySet is expected O(1) with an unspecified iteration order; ConcurrentSkipListSet is expected O(log n) and gives you neighbours, ranges and ascending iteration. If no caller queries a range, the hash-backed set is simply faster.
The ordered set is for the cases where the ordering is doing work: the smallest element matters (pollFirst), the next element after a value matters (ceiling), or a window of values matters (subSet). Those are ordered indexes, expiry queues and range membership checks, not general-purpose shared sets.
Common misconception: That the sorted set is the safer default because it does more. It is slower per operation and it adds rules the unordered set does not have, null handling among them.
Follow-up: What exactly does it do with a null?
contains(null) on this set: false, or an exception?+
An exception. contains delegates to the map's containsKey, which rejects null keys with NullPointerException, so a null filter value blows up instead of yielding an empty result.
HashSet answers false for contains(null), which is why the reflex exists; TreeSet throws as well, for the same reason (there is nothing to compare against). Any code path where the element can be null needs its own check before the call.
Common misconception: That contains answers false for anything absent. HashSet and CopyOnWriteArraySet return false for a null argument; this class throws, and so does a naturally-ordered TreeSet, because the argument has to be compared and null has no order.
Follow-up: And contains with the wrong type?
The Javadoc says size is not a constant-time operation. Is that still true?+
The warning is inherited from an older implementation that counted by traversal. Today the call delegates to the map, which keeps a running count, so it does not walk the set. The count is still a snapshot, which is the part the Javadoc's advice is about.
Any size that other threads can change is an observation, not a fact: a size check followed by an add is a race in the same way it would be on any other concurrent collection. If a bound matters, enforce it with an atomic operation or with a counter you own.
Common misconception: That the warning is stale in both halves. The traversal is gone; the snapshot problem is not.
Follow-up: How would you enforce a maximum size on this set?
Are the subsets live, and what happens if you write through them?+
Live: subSet, headSet and tailSet wrap the map's range views, so changes on either side are visible on the other. Adds beyond the range throw IllegalArgumentException.
Because they are views, clearing one removes element after element from the original set: atomic per element, not as a batch. Iteration over a view is weakly consistent like the set itself, with the bound checked as it walks, so it stops at the range end without scanning further.
Common misconception: That a subset is a copy, the way stream filter produces a new collection. It is a window, and writes travel both ways.
Follow-up: What about a descending view?
Two players with the same score go into a leaderboard built on this set. What happens?+
Only the first is kept: the comparison returns zero, so the second add returns false and its object is discarded. Ranges and counts are then wrong about the missing player, and nothing warns you.
The leaderboard key has to be composite: score plus tiebreaker, ordered by score descending and then by player id, so distinct players never compare equal. The natural-order rule is the same one TreeMap and every sorted collection share.
Common misconception: That equals would save the second player, or that add would overwrite the first. Neither: a sorted set keeps the incumbent and reports false.
Follow-up: Where else does a compare-equal collision show up?