The Plain Picture#
A shared notebook where eight people write at the same time. A normal notebook gets torn pages and overwritten lines. A concurrent notebook has a separate lock on every page, so people writing on different pages never wait for each other.
The Real Names#
HashMapis not thread-safe. Concurrent writes can lose entries, corrupt the bucket structure (Collections, From the Inside Ch 4) and even throw.ConcurrentHashMap(CHM) is the thread-safe map to use:reads never block;
writes use CAS to place a node in an empty bucket and lock only that one bucket (its first node) otherwise — so threads writing to different buckets don't wait for each other (since Java 8; older versions used 16 "segments");
compute,merge,computeIfAbsent,putIfAbsentare atomic per key;no
nullkeys or values (anullfromgetmust unambiguously mean "absent").
Other thread-safe collections:
CopyOnWriteArrayList(copies the whole array on every write — great for lists read constantly and changed rarely, like a listener list),ConcurrentLinkedQueue(lock-free queue),ConcurrentSkipListMap(a concurrent sorted map — the thread-safeTreeMap), and theBlockingQueues (Ch 7).Collections.synchronizedMap(map)/synchronizedList(list)wrap a collection with one big lock — correct but slow under contention, and iteration still needs manual locking. Prefer the concurrent classes.
Under the Hood — measured, three times#
Eight threads each counting 10,000 events into 100 keys (expected total: 80,000):
expected 80000 | HashMap: 59312 (tasks crashed: 2) | CHM.merge: 80000 | CHM get-then-put: 14838
expected 80000 | HashMap: 79248 (tasks crashed: 0) | CHM.merge: 80000 | CHM get-then-put: 12698
expected 80000 | HashMap: 39831 (tasks crashed: 4) | CHM.merge: 80000 | CHM get-then-put: 19797Read each column:
HashMap— wrong every time, by a different amount, and in two runs some threads crashed outright from the corrupted internal structure. Run it once more and it might look almost right (79,248) — which is how these bugs slip through testing.ConcurrentHashMap.merge— exactly 80,000 every time, becausemergedoes its read-modify-write atomically.ConcurrentHashMapwithgetthenput— still badly wrong, even though CHM is "thread-safe"!
That last column is the important lesson:
Integer cur = map.get("views"); // step 1: read
map.put("views", cur + 1); // step 2: write — another thread may have written in betweenEach call is thread-safe on its own, but the sequence isn't atomic. This check-then-act (or read-modify-write) race is the most common concurrency bug in real Java code. A thread-safe collection doesn't make your combination of calls thread-safe. Use the atomic compound methods:
map.merge("views", 1, Integer::sum); // atomic increment
map.computeIfAbsent(userId, id -> new ArrayList<>()); // atomic "create if missing" (keep the function short and side-effect free)
map.putIfAbsent(key, value); // atomic "insert only if absent"
map.compute(key, (k, v) -> v == null ? 1 : v + 1); // atomic arbitrary updateCheck yourself
4 questionsHow does ConcurrentHashMap allow concurrent writes without one global lock?
Show answerHide answer
It uses CAS for empty buckets and locks only the individual bucket being modified; reads don't lock.
Why was "CHM get-then-put" wrong even though CHM is thread-safe?
Show answerHide answer
The two calls together form a non-atomic read-modify-write; other threads' updates between them were lost.
How do you increment a counter in a CHM correctly?
Show answerHide answer
map.merge(key, 1, Integer::sum) (or compute).
When is CopyOnWriteArrayList a good choice?
Show answerHide answer
When the list is read/iterated very often and modified rarely (e.g. event listeners).