Video in progress

Strong Middle 🧺 Collections

What is ConcurrentSkipListMap, and when do you pick it over ConcurrentHashMap?

It is a sorted concurrent map based on a skip list that works without locks (using CAS): get/put are O(log n), and it has the NavigableMap methods ceilingKey, headMap and pollFirstEntry. If you need ordering or range queries in a multithreaded setting, you pick it instead of ConcurrentHashMap.

📖 Answer

A skip list is a linked list with several levels. The bottom level holds all elements, and each higher level holds fewer, randomly chosen elements that act as an "express lane". A search starts at the top and goes down, which is O(log n) on average. Unlike a tree, it doesn't need a big restructuring to stay balanced, which makes it easier to build without locks.

A practical example is an order book sorted by price, or scheduled tasks:

ConcurrentNavigableMap<Long, Order> bids = new ConcurrentSkipListMap<>(Comparator.reverseOrder());

bids.put(price, order);                         // many threads write
Map.Entry<Long, Order> best = bids.firstEntry(); // the highest price
bids.headMap(limit).clear();                    // drop everything above the limit

The price you pay:

  • it is slower than ConcurrentHashMap (O(log n) versus O(1)) and uses several nodes per element, so more memory;
  • size() is not a constant-time operation: it walks the list, and the result is approximate while other threads are writing;
  • iteration is weakly consistent, and firstEntry followed by remove is not atomic. Use pollFirstEntry for that.

There is a set counterpart too: ConcurrentSkipListSet. If you don't need ordering, ConcurrentHashMap is almost always better.