Concurrent Data Structures
How thread-safe collections avoid one big lock (striped locks, compare-and-swap, copy-on-write, striped counters), with ConcurrentHashMap, CopyOnWriteArrayList and LongAdder explained from their docs.
Overview
A concurrent data structure is a collection that many threads can use at once without the caller adding locks. The simplest way to get one is to put a single lock around every method. That is correct but slow under load, because every thread waits for every other thread, even readers and even threads touching different keys.
The structures in java.util.concurrent and their equivalents elsewhere use a handful of techniques to let threads proceed together. Interviewers ask how they work (usually ConcurrentHashMap), which one fits a workload, and why a thread-safe map still does not make your own code thread-safe.
Thread-safe methods are not thread-safe code
Each call on a concurrent map is atomic, but two calls in a row are not. 'If the key is missing, put it' done as two calls races: both threads see it missing and both put. The same holds for a map wrapped by Collections.synchronizedMap, whose docs also require you to lock the map yourself while iterating it.
Here is the race on a map of counts, starting with counts["x"] at 0.
- Thread A reads counts["x"] and gets 0.
- Thread B reads counts["x"] and also gets 0.
- Thread A writes 1.
- Thread B writes 1. The count is 1, and one update is lost.
The fix is to ask the structure for one atomic operation that does the whole thing: merge, compute, computeIfAbsent or putIfAbsent in Java, or a lock held across both steps.
Interview questions
- How does ConcurrentHashMap perform better than a synchronized HashMap?
- What are lock-free data structures, and when should you use them?
- When should you use LongAdder instead of AtomicLong?
- Which concurrent collection would you pick, and why?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio