Concurrent collections question 66 of 180 junior
Why is Hashtable or Collections.synchronizedMap worse than ConcurrentHashMap?
- They are not thread safe
- Correct: They lock the whole map for every operation, and compound actions still race even though each call is atomic
- They do not allow null values
- They are deprecated
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.
Quiz yourself on Concurrent collections Suggest a correction