Video in progress

Strong Middle 🧵 Concurrency

What do you use when you need a sorted Map in multithreaded code? How does ConcurrentSkipListMap work?

TreeMap is not thread-safe, and Collections.synchronizedSortedMap makes everything go through one lock, one at a time. ConcurrentSkipListMap is based on a lock-free skip list, keeps keys in order, and runs get, put and range queries in parallel in O(log n) on average.

📖 Answer

A skip list is a linked list with several levels. The bottom level holds all the elements in order, and the upper levels hold randomly chosen "express stops". A search starts at the top and goes down, so it's O(log n) on average. The difference from a tree is that there's no rotation for balancing, which makes it much easier to build lock-free with CAS.

When you need it: where key order matters and many threads write.

// price -> total volume at that price (one side of an order book)
ConcurrentNavigableMap<BigDecimal, Long> bids =
        new ConcurrentSkipListMap<>(Comparator.reverseOrder());

bids.merge(price, qty, Long::sum);                      // atomic
Map.Entry<BigDecimal, Long> best = bids.firstEntry();   // best price
ConcurrentNavigableMap<BigDecimal, Long> top = bids.headMap(limitPrice, true);

Another typical case is an index by time: ConcurrentSkipListMap<Instant, Event> and clearing the expired entries with headMap(now).clear().

What to know:

  • size() is O(n) and approximate under concurrent changes;
  • the iterator and the subMap views are weakly consistent: no CME, but they may or may not see changes made during the traversal;
  • null keys and values are forbidden;
  • if you don't need ordering, ConcurrentHashMap is almost always faster and more compact in memory.

If you need a set, there's ConcurrentSkipListSet, built on top of this map.