Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Concurrency

    Concurrent Collections

    HashMap is not thread-safe. Concurrent writes can lose entries, corrupt the bucket structure (07javacollectionsinternals.md Ch 4) and even throw.

    Chapter 8 of 124 min readOften asked in interviews

    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#

    • HashMap is 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, putIfAbsent are atomic per key;

      • no null keys or values (a null from get must 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-safe TreeMap), and the BlockingQueues (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):

    Output
    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: 19797

    Read 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, because merge does its read-modify-write atomically.

    • ConcurrentHashMap with get then put — still badly wrong, even though CHM is "thread-safe"!

    That last column is the important lesson:

    Java
    Integer cur = map.get("views"); // step 1: read
    
    map.put("views", cur + 1); // step 2: write — another thread may have written in between

    Each 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:

    Java
    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 update

    Check yourself

    4 questions
    1

    How does ConcurrentHashMap allow concurrent writes without one global lock?

    Show answer

    It uses CAS for empty buckets and locks only the individual bucket being modified; reads don't lock.

    2

    Why was "CHM get-then-put" wrong even though CHM is thread-safe?

    Show answer

    The two calls together form a non-atomic read-modify-write; other threads' updates between them were lost.

    3

    How do you increment a counter in a CHM correctly?

    Show answer

    map.merge(key, 1, Integer::sum) (or compute).

    4

    When is CopyOnWriteArrayList a good choice?

    Show answer

    When the list is read/iterated very often and modified rarely (e.g. event listeners).