Lesson · Concurrent Collections
ConcurrentSkipListMap: the sorted map that stays fast
17 min readConcurrentSkipListMap
Sorted and concurrent is the one combination java.util left open: there is no ConcurrentTreeMap. ConcurrentSkipListMap fills it with a linked list that grows express lanes by coin flip, so lookups are expected O(log n) without rotations and without a global lock. This lesson covers the mechanism, the navigable surface it inherits, and the point where a plain concurrent map is simply better.
There is no ConcurrentTreeMap
The need is easy to arrive at: a shared map whose keys must stay in order. Sessions by expiry time, events by timestamp, players by score. The single-threaded answer is TreeMap, and the obvious way to share one is the synchronized wrapper.
That wrapper serializes everything. Every read takes the map-wide monitor, so lookups queue behind writes, and a range scan holds the monitor for the whole walk even when nobody is touching the range. Nothing about it is incorrect; it is just the slowest thing on a contended path, and no test will ever tell you, because the failures are throughput, not correctness.
Map<Long, String> index = Collections.synchronizedSortedMap(new TreeMap<>()); index.get(expiry); // takes the map-wide monitor index.put(expiry, "s-42"); // and so does every other write for (Map.Entry<Long, String> e : index.tailMap(now).entrySet()) { report(e); // the walk holds the monitor for its whole length } // java.util.concurrent ships no ConcurrentTreeMap. The class that fills the // gap is a different data structure, not a locked tree.
Sorted and concurrent is a real gap in the library. Rotations are the reason: repairing a balanced tree is not a lock-free operation. What fills the gap is a skip list.
A linked list with express lanes
A skip list is a sorted linked list with extra lanes. The base lane carries every key in order. Above it sit index lanes: each index node points right to the next indexed node and down to the same key one lane lower, so a lane is a shortcut you follow for a while and then leave.
Heights are decided once, at insert, by coin flips, and never revisited. The JDK hardwires p = 0.5 for the flips above the first index level, with the practical result that about one node in four carries an index at all: half of those reach one level up, a quarter reach two, and so on, up to a cap of 62 levels.
A search starts at the head of the top lane: move right while the next key is smaller than the target, drop a level when it overshoots. Every drop leaves a stretch behind, so a lookup touches a few nodes per lane instead of walking the base. Expected O(log n) probes, and not one rotation anywhere in the structure.
- The height is local. A node draws its own height at insert, and its neighbours are never rearranged to make room for it. That is why an insertion is a handful of pointer writes instead of a repair.
- Sparse on purpose. Only a quarter of the nodes carry an index at all, and each level above the first halves that count again. The class notes the total space is slightly less than a TreeMap holding the same entries.
- The cap is 62 levels, which the source describes as appropriate for up to 2^63 elements. Extra lanes past that would be dead weight rather than extra speed.
- Lanes only guide searches. Correctness lives in the base lane: if an index splice ever fails, the search still finds the key, it just takes fewer shortcuts on the way.
No rotations, just coin flips. A balanced tree earns its shape deterministically and repairs every violation; a skip list draws its shape once and lives with a statistical guarantee. That single trade is what buys the lock-free write path.
Skip list · search 42, insert 42, range 45 to 65
Start: a sorted map with three lanes. Base carries every key; level 1 and level 2 are index lanes that skip across it. 20 keys, heights drawn at insert time, nothing balanced.
Why a search never takes a lock
Reads take no locks, and a lookup is never staler than the moment the call started: the class documents exactly that. It works because every link is volatile and every structural change is a compare-and-set on a single pointer.
An insert links the new base node with one CAS on its predecessor, then splices index nodes upward, one CAS per level, re-finding the splice point whenever it loses a race. A removal is staged in two steps: the node value is CAS-ed to null first, which is what tells concurrent readers the node is gone, and a small marker node is swapped in so that the physical unlink can be finished by whichever thread meets it first.
The head is the only shared piece of state. A new top lane is added by CAS on the head pointer, and a heuristic lowers the head by one level when the top lanes look empty after a run of removals. No map-wide lock appears anywhere in that path.
- Null is the delete marker. Setting a node value to null is step one of removal. That is the implementation reason the map refuses null values, on top of the API reason: a null return could not be told apart from an absent mapping.
- A losing CAS retries, it never waits. Under contention, updates re-run the search from the head. The class notes the practical effect is a lower effective promotion rate rather than parked threads.
- Mutative operations are linearizable against each other, and reads return a non-null value that held at some point during the call. Neither ever blocks the other.
One CAS per pointer, no rebalancing, no lock. A reader only ever follows volatile links, so a writer cannot block it, and a writer only ever CAS-es its own pointers, so a reader cannot block it either.
Skip list · lanes, links, coin flips
heights are drawn at insert and never revisitedEvery key sits in the base lane; the lanes above hold the same keys at sparser intervals. A search walks right while the next key is smaller than the target and drops a lane when it overshoots, so it crosses the sorted list in a few hops instead of a walk.
three links, and what happens to each
right
the next node in the same lane. A new index node is spliced in with a CAS, and a lost race is simply retried.
down
the same key one lane lower. Fixed when the node is created, so a failing index splice cannot break a search.
next
base lane only: the sorted neighbour. Linking a new key is one CAS, and a removal nulls the value first.
how a node gets its height
about 1 in 4
a node gets an index at level 1 at all. The rest live only in the base lane.
1 in 2
promoted one lane higher, so it also appears in level 2.
1 in 2
promoted again, level 3, and so on while the draws keep saying yes.
cap 62
the level ceiling in the JDK, enough for 2^63 elements. No draw can exceed it.
The draws are independent and nothing repairs a bad run, which is why the cost is expected O(log n) and not a hard bound: an unlucky structure degrades toward a walk of the base lane.
The navigable surface you get
The class implements ConcurrentNavigableMap, so the whole TreeMap surface is present: both ends, the four neighbour lookups, range views, and a descending view.
Range methods return views over the same map, not copies. Creating one stores two bounds; reading through it walks the same nodes, and writing through it edits the same entries. The two-argument forms are half-open, so subMap(from, to) excludes to.
| Call | Returns | Worth knowing |
|---|---|---|
| firstKey / lastKey | the smallest and largest key | throw NoSuchElementException when empty; firstEntry and lastEntry return null instead |
| pollFirstEntry / pollLastEntry | removes and returns an end | one atomic step: a sorted work queue with no extra structure |
| floorKey / ceilingKey | greatest key at or below, least key at or above | return null for an absent argument; they never demand that the key exists |
| lowerKey / higherKey | the same, strictly below or strictly above | the navigable quartet: lower, floor, ceiling, higher |
| headMap / tailMap / subMap | a view over a key range | views, not copies; writes through the view edit the same map |
| descendingMap / descendingKeySet | the same entries in reverse order | correct but slower: the class notes descending views and iterators are slower than ascending ones |
| putIfAbsent / replace / remove(k, v) / compute / merge | the ConcurrentMap surface, overridden here | the read and the write become one operation; the mapping function itself may still run more than once under contention |
| entry.setValue | throws UnsupportedOperationException | entries are snapshots; change a value with replace or the compute methods |
- Keys are unique under the comparison, not under equals. Two entries that compare equal are one key, and the second put replaces the first. A leaderboard keyed by score alone therefore keeps one player per score, tie or no tie.
- The order comes from the constructor: natural ordering by default, or a Comparator you pass in. The consistency-with-equals rule is the same one TreeMap lives by, and the Comparable vs Comparator lesson owns the full contract.
The ordering is the product, not decoration. pollFirstEntry is a sorted work queue, floorKey is an interval boundary, subMap is a window. If none of those calls appear in your design, the sorted map is the wrong tool.
Ascending, weakly consistent, and cheap to measure
Iterators walk ascending key order and are weakly consistent: they never throw ConcurrentModificationException, and they reflect the map as of some point at or after the iterator was created. An entry added inside your range may or may not appear. That is the entire promise: safe iteration of a busy map, never a snapshot.
size() is cheap here, because the map keeps a count in a LongAdder and updates it on every structural change, so reading it does not walk the lanes. It is still a snapshot, so it cannot support an invariant on a map that other threads are editing.
Bulk operations are the documented exception. putAll, clear, containsValue, equals and toArray are not atomic, so an iterator running alongside a putAll can see part of the batch and not the rest.
- Iterating and removing is supported. The iterator remove delegates to the map remove, which is one atomic removal per call.
- Entries are snapshots without setValue. Every Map.Entry handed out by this map and its views rejects setValue with UnsupportedOperationException; change values with replace, putIfAbsent or compute.
- No null keys or values in any method. get(null) and containsKey(null) throw NullPointerException before any comparison happens, so null checks belong in your code.
Weak consistency is safety, not accuracy. No exceptions, no snapshot, no isolation. An invariant that needs a frozen view wants a copy of the range you care about, not an iterator over the live map.
When it fits, and when it does not
Reach for it when the ordering itself is doing work.
- Sorted indexes: a secondary index keyed by the column you range-scan, written by every writer and read by every query.
- Range scans: events in the last minute, invoices in a quarter, keys between two prefixes, all as subMap or tailMap views.
- Sliding windows and rate limits: store request timestamps as keys and drop everything below the window start; the boundary you want is floorKey(now - window).
- Expiry sweeps: key sessions by expiry time, then drain headMap(now) and close what is due.
- Leaderboards: the top N is a walk of the descending view, and a rank lookup is a key. A composite key is mandatory once scores can tie.
- Skip it when the order earns nothing. A hot counter or a memo cache wants ConcurrentHashMap: expected O(1), a better constant factor, and no ordering contract to keep. Skip it as well when you need a guaranteed worst case, because the honest alternative there is a lock around TreeMap, where you pay the serialization openly instead of paying a probabilistic tail.
You pay log n only when you query ranges. If no caller ever asks for a neighbour or a sub-range, an unordered concurrent map is strictly better, and the ordering cost buys nothing at all.
The decision walk-through
Choosing between the sorted concurrent map, its neighbours, and a lock, in order:
- Is the key order part of the problem? If nothing queries a range or a neighbour, use ConcurrentHashMap and stop here.
- Can two records share a key? Scores, coarse timestamps and any non-unique value need a composite key (score plus id) so that the comparison never returns zero for distinct records.
- Does the key type have a total order? Natural ordering, or a Comparator at construction. The order must be consistent with equals, or lookups silently miss what is in the map.
- Will a caller want both ends or a window? Then the navigable surface is the point: firstKey and lastKey, floor and ceiling, subMap, descendingMap.
- Is the iterator allowed to disagree with the map? If you need exactness, copy the range you care about instead of iterating the live map.
- Do you need a hard worst case? A lock around TreeMap is the option that guarantees one. A skip list offers expected O(log n) with a tail that is O(n) and vanishingly unlikely.
Sorted, concurrent and cheap to read: expected O(log n) for get, put, remove and containsKey, no global lock, ascending weakly consistent iterators, and range queries that stop nobody else. The price is a log factor and a probabilistic structure.
A skip list is not a balanced tree
ConcurrentSkipListMap is not a concurrent TreeMap, and the difference is not cosmetic. A red-black tree has a hard O(log n) guarantee; a skip list has an expected O(log n) that holds because random heights spread the keys across lanes. A run of unlucky draws leaves nodes without lanes, and a search degrades toward a walk of the base lane. The probability is negligible and the design accepts it, but the guarantee is statistical rather than structural. If your system needs a hard bound, take the lock and use TreeMap: that trade is visible and honest, and it is the reason the JDK never shipped a ConcurrentTreeMap.
Interview angles
java.util.concurrent has no ConcurrentTreeMap. What does it ship instead, and why?+
ConcurrentSkipListMap. A balanced tree needs structural repairs that are hard to make lock-free, while a skip list gets tree-like search from random heights, so its updates are pointer CAS operations.
The structure is two-dimensionally linked: base nodes hold the entries, index nodes hold right and down pointers. Insertion links the base node with one CAS on the predecessor, then splices index nodes upward, one CAS per level. The result is expected O(log n) for get, put, remove and containsKey with no map-wide lock.
Common misconception: That it is a TreeMap with different internals. The guarantee is different (expected, not worst case), and the entry and iterator behaviour is different too.
Follow-up: What does weakly consistent mean for its iterators?
How do searches stay fast without ever taking a lock?+
They follow the lanes: at each level, move right while the next key is smaller and drop a level when it overshoots. A search touches a few nodes per lane plus a short run of the base lane, reading volatile pointers the whole way.
Removal is staged so readers never need to wait for it: the node value is CAS-ed to null first, which is what marks the node as gone, then a marker node replaces its next pointer so any thread can complete the unlink. Because null values are the delete marker, the map cannot accept null values at all.
Common misconception: That a failed CAS means the operation failed. It means the world moved: the operation re-reads and retries, and the caller sees nothing.
Follow-up: How expensive is size() on this class?
Is an iterator over this map a snapshot?+
No. Iterators are weakly consistent: no ConcurrentModificationException, and they show the map as of some point at or after creation.
A true snapshot would need a lock or a copy on every iteration, which is exactly what this class exists to avoid. Ascending iteration is the fast direction; the class notes descending views and iterators are slower. The entries handed out are snapshots whose setValue throws UnsupportedOperationException.
Common misconception: That size() plus iteration gives a consistent view. Neither is a snapshot, so a check-then-iterate pattern proves nothing about the map.
Follow-up: So how do you iterate safely when you need an exact set of entries?
Two threads increment a counter held in this map. Does the map make that safe?+
Only if you use its compound operations. merge, compute and putIfAbsent are overridden here and atomic; a get followed by a put is still two operations, and the increment between them can be lost.
The atomic overrides are the whole reason ConcurrentMap exists. Anything of the form read, decide, write has to become one of those calls, or move to an AtomicLong when the value is a single number and the key never changes.
Common misconception: That the map also protects the values. It protects the mapping: two threads updating one mutable value object are still on their own.
Follow-up: And how does size() behave under those concurrent updates?
Why are null keys and values refused when HashMap allows them?+
A null return value could not be distinguished from an absent mapping, and internally a null value is exactly how a removed node is marked before it is unlinked. Null keys have a third problem: they would have to be compared, and null has no place in an order.
get(null) and containsKey(null) throw NullPointerException rather than returning null or false, so even a defensive lookup needs a null check before the call. Bulk operations have the same strictness.
Common misconception: That a concurrent map is a thread-safe HashMap with the same laxness about nulls. The API is narrower on purpose.
Follow-up: What else is narrower than HashMap here?
A leaderboard is keyed by score with this map. What goes wrong when two players tie?+
They are the same key. The comparison returns zero, so the second put replaces the first and one player vanishes from the board.
Keys are unique under the map comparison, not under equals, which is the rule TreeMap and every sorted structure share. The fix is a composite key: score plus a unique tiebreaker such as player id, so that distinct records never compare equal.
Common misconception: That equals decides identity. In a sorted map, the comparison does, and equals is consulted only for the values it stores.
Follow-up: What happens if the comparison is not consistent with equals?