Java Concurrency Interview

Concurrent collections question 66 of 180 junior

Why is Hashtable or Collections.synchronizedMap worse than ConcurrentHashMap?

A synchronized wrapper takes one lock around every method, so all threads serialise even when touching unrelated keys. ConcurrentHashMap locks a single bin, so writers to different keys proceed in parallel and readers usually take no lock at all.

The second half matters more. Per-method atomicity does not make sequences atomic:

if (!map.containsKey(k)) {  // atomic
    map.put(k, compute());  // atomic, and the pair is still a race
}

ConcurrentHashMap gives you the atomic compound operations that fix this: putIfAbsent, computeIfAbsent, compute, merge, and the two-argument remove and replace.

collections chm

Quiz yourself on Concurrent collections Suggest a correction