Lesson · Concurrent Collections
Why Concurrent Collections: wrappers, locks and weak consistency
15 min readWhy Concurrent Collections?
A synchronized wrapper makes every call atomic and still leaves your program racing, because the bugs live between calls. The java.util.concurrent collections exist to shrink the gap: narrow locks, named compound methods, and iterators that never throw.
The wrapper that makes each call safe
Collections.synchronizedMap(new HashMap<>()) returns a map whose every method runs under one mutex. Reads, writes, size, containsKey: one lock, acquired and released around each call. What you get is a collection in which no single call can be observed half finished.
What you do not get is a collection in which a sequence of calls is protected. The lock is released the moment containsKey returns and taken again when put runs, so every decision your code makes between two calls is made outside the lock.
Iteration is the documented exception that proves the rule. The wrapper does not hold the mutex while a for loop walks one of its views, and the backing map's fail-fast iterator only tolerates structural change that the iterator itself makes. The javadoc instruction is explicit: synchronize on the wrapper while traversing any view, and synchronize on the map rather than on the view you are iterating.
Map<String, Integer> counts = Collections.synchronizedMap(new HashMap<>()); Set<String> keys = counts.keySet(); // the view has no lock of its own synchronized (counts) { // lock the wrapper, not the view for (String key : keys) { System.out.println(key + "=" + counts.get(key)); } }
The wrapper locks method calls. Your program is made of sequences of calls, and the gap between them is exactly what the lock leaves open.
Atomic calls, racing use
The classic shape is check then act: containsKey then put, get then a conditional set, size then remove. Two threads, two interleavings, one entry where you expected two. Every call was atomic; the sequence was not.
This is a lock granularity problem rather than a wrapper problem. The lock covers the call, and the bug lives between calls. Holding the wrapper's mutex across both calls does fix it, at the price of writing lock-and-check code at every call site.
The alternative is to stop describing the operation as two calls. putIfAbsent, computeIfAbsent, compute, computeIfPresent and merge each name a whole decision and perform it as a single operation. Both a synchronized wrapper and a ConcurrentHashMap implement those atomically: the wrapper holds its one mutex, the concurrent map works on one bin. The difference is not correctness, it is how much of the map the decision blocks.
| Scenario | Collections.synchronizedMap | ConcurrentHashMap |
|---|---|---|
| One get or one put | every call takes the same mutex | reads take no lock; a write touches one bin |
| check then act across two calls | races: the gap sits outside the lock | races too: the gap is between two operations |
| putIfAbsent / compute / merge | atomic, and it blocks every other call | atomic, and it blocks one bin |
| Iteration while others mutate | must lock manually; forgetting throws ConcurrentModificationException | weakly consistent iterator: never throws |
| Read throughput under load | capped: readers queue behind each other | scales with cores while the table is stable |
| Null keys and values | whatever the backing map allows | rejected with NullPointerException |
A synchronized wrapper makes each call atomic, not each use. The gap between two calls is where the bug lives, and no wrapper can close a gap it cannot see.
One lock is a funnel
Every call into the wrapper takes the same mutex, so two threads reading two different keys still take turns. Nothing about a read needs exclusion; the wrapper supplies exclusion anyway, because a wrapper can only serialize what it wraps.
The cost appears as a queue rather than a wrong answer. Throughput flattens as threads are added: the collection becomes the serial part of an otherwise parallel program, and idle cores wait on one monitor.
Two second-order traps come from the same design. The lock covers your callback, so forEach on the wrapper runs your action while holding the mutex and a slow action stalls everyone. The lock is also invisible at the call site: nothing in map.get(k) says a global lock was taken, so readers keep being written as though reads were free.
- Readers queue behind unrelated writers. One mutex means one queue, whatever keys are involved.
- Callbacks run inside the lock. A
forEachbody executes with the collection mutex held, so keep it short and do not reach into other synchronized state from it. - Contention grows with cores. Adding threads lengthens the queue; it does not shorten the critical section.
- There is no read path that skips the lock. A read-mostly workload pays as though it were write-heavy.
One mutex makes the map the slowest part of the program, and it does so one perfectly correct call at a time.
What a weakly consistent iterator promises
Concurrent collections replace fail-fast iterators with weakly consistent ones, and the package wording is worth reading literally: a weakly consistent iterator is guaranteed to traverse the elements as they existed when it was created, and may (but is not guaranteed to) reflect modifications made afterwards. It never throws ConcurrentModificationException.
Three consequences follow. A traversal under concurrent writes is safe. The exact set of elements you see is not specified. And because the promise is permissive rather than restrictive, code that needs a fixed view has to take its own snapshot.
That is the line between the two concurrent families. ConcurrentHashMap gives weak consistency: walk it while others write and the view is never broken, with no promise about which updates are in it. CopyOnWriteArrayList gives a real snapshot: the iterator holds the array as it was, so later writes are invisible to it. Weakness buys scale, snapshots buy certainty.
Weak consistency trades snapshots for scaling. You give up the promise of a frozen view and get a traversal that survives any write rate.
The java.util.concurrent design contract
The concurrent collections are not the old collections with a lock bolted on. They are a redesign around a few decisions, and the family makes those decisions the same way. The maps also inherit the package visibility guarantee: whatever a thread did before putting a value into a concurrent map happens-before the thread that retrieves it, which is what lets a concurrent collection act as a handoff point with no extra synchronization.
- Atomic at the collection level. One call is one operation with one linearization point:
get,put,sizeand their siblings are safe from any thread, with no lock for you to hold. - Compound actions are named methods.
putIfAbsent,computeIfAbsent,compute,computeIfPresent,merge,remove(key, value),replace. If your logic needs two calls, the collection probably ships it as one. - Narrow locks instead of one lock. Reads take no lock at all and writes work on a single bin, which is the design the wrapper's single mutex exists to replace.
- Weakly consistent traversal. Iterators never throw under concurrent writes, and they never promise a snapshot. Take a copy when the view has to be fixed.
- No nulls in the maps. A concurrent map rejects null keys and values, which removes the difference between a missing entry and an entry holding nothing, a distinction the atomic methods need.
Atomic calls, named compound methods, narrow locks, no nulls: four decisions that each remove a way to hold a lock too long.
One gate, or one gate per bin
same threads, same calls, two access paths
Collections.synchronizedMap
Every call, read or write, passes through the same mutex.
one mutex for the whole map
One call in, one call out. Unrelated keys wait on each other, so the queue, not the map, sets the pace of the program.
ConcurrentHashMap
Nothing is shared between operations that touch different bins.
The wrapper guarantees one thing at one scope: the whole map, for the duration of one call. The concurrent map splits that scope by bin, so two operations that never touch the same bin never interact. The weaker-looking guarantee is the stronger one to run, because it is the only one that leaves room for two threads to make progress at once.
Watch the funnel, then watch it disappear
The lab below runs three workloads against both designs. Reads only shows what one mutex does to work that cannot conflict. Mixed read and write shows a writer blocking readers it shares nothing with. Check then act is the informative one: it fails on both collections, and the third option is the named method that removes the second call.
Switch designs inside a scenario and compare the lock strip with the lane states. The outcome panel judges the whole scenario, not the current beat.
Concurrent collections lab · one workload, two designs
workload
design
lock state
held by reader 1 · reader 2 queued
inside get("a")
waiting for the mutex
Both readers call get on different keys. The wrapper takes its one mutex before the call, so the second reader waits even though nothing is being written.
outcome · reads only · Collections.synchronizedMap
reads queue: throughput is capped by one mutex
Nothing in this workload needed exclusion. Every read took the same lock anyway, so two cores produce the read throughput of one, and adding threads only lengthens the queue.
When a wrapper is still the right answer
Concurrent collections are not a blanket replacement, and treating them as one is a recognizable interview mistake. The wrapper is right when mutation is rare and you control every access, or when the collection you need has no concurrent counterpart.
Most families do have one: ConcurrentHashMap for HashMap, ConcurrentSkipListMap for TreeMap, ConcurrentLinkedDeque and LinkedBlockingDeque for ArrayDeque, PriorityBlockingQueue for PriorityQueue. The notable gap is LinkedHashMap, particularly in access-order mode, which is why a hand-written LRU cache often keeps a synchronized wrapper plus one explicit lock.
- Single-threaded? Use the plain collection. A wrapper or a concurrent map adds cost and buys nothing.
- Shared, with compound logic? Prefer the concurrent collection and its named methods; if none exists, keep the collection private and take one lock around the whole sequence.
- Shared, read-mostly, immutable after startup? Publish an immutable snapshot and swap the reference; the read path then contains no lock at all.
- Shared, read-mostly, rarely mutated?
CopyOnWriteArrayListor a swap-the-reference store; readers never lock. - Shared and write-heavy?
ConcurrentHashMapor a queue. A single mutex is the bottleneck, and a wrapper cannot fix its own granularity.
Choose by counting writes, not by habit. Rare writes with full control over every access is exactly where the wrapper is honest.
The lock you were supposed to take
Collections.synchronizedMap does not lock your iteration. The javadoc says to synchronize on the wrapper while traversing any of its views, and to synchronize on the map rather than on the keySet, because the view has no lock of its own. Skip that step and the failure is a ConcurrentModificationException thrown from the iterator, or, when the best-effort check misses it, a walk that quietly returns the wrong elements. The wrapper is safe per call; the loop is your responsibility.
Interview angles
Why is Collections.synchronizedMap not enough by itself?+
It makes each method call atomic and nothing more. Iteration is not a method on the wrapper, so the javadoc requires you to synchronize on the map while traversing a view, and compound logic such as containsKey-then-put spans two calls with the lock released in between.
So is a compound action a race on a synchronized wrapper?+
Yes, unless you hold the wrapper mutex across both calls. Two threads can both observe the key absent and both write, and the second write replaces the first. The wrapper serializes calls, not the decision your code makes between them.
Common misconception: That thread-safe means operations that call the map twice are safe.
What exactly does a weakly consistent iterator guarantee?+
It never throws ConcurrentModificationException, and it traverses the elements as they existed when it was created. Whether it reflects later modifications is unspecified, so it is neither fail-fast nor a snapshot.
Common misconception: That weakly consistent means the iterator walks a frozen copy of the collection.
Why is ConcurrentHashMap more scalable than a synchronized wrapper?+
Granularity. The wrapper takes one global mutex for every call, so readers queue behind writers and behind other readers. ConcurrentHashMap takes no lock on the read path, uses CAS to fill an empty bin, and synchronizes on the bin head only when a write lands on an occupied bin.
Both a wrapper and ConcurrentHashMap implement putIfAbsent atomically. Where is the difference?+
One lock against one bin. The wrapper holds its single mutex while the operation runs, so every other call waits. The concurrent map scopes the operation to the bin holding the key, so unrelated keys keep moving.
That is also why a mapping function must be short and must not touch the map: the bin holding the key is busy for the duration, and a nested update on the same map can block or throw.
When is a wrapper still the right choice?+
When mutation is rare and you control every access, or when the collection has no concurrent counterpart, such as an access-order LinkedHashMap cache. You then hold one explicit lock around the whole compound sequence and accept that reads serialize.
Follow-up: How would you publish that cache for lock-free reads?