Video in progress
Which would you pick, ConcurrentHashMap or Collections.synchronizedMap, and why?
Usually ConcurrentHashMap: reads are lock-free, writes block only one bucket, and it has atomic operations like computeIfAbsent and merge. synchronizedMap takes one shared lock on every call and needs a manual synchronized block for iteration.
📖 Answer
synchronizedMap is a plain wrapper: every method does synchronized (mutex) { m.get(...) }. One "big lock". As load grows, threads pile up in a queue.
Iteration is a separate problem:
Map<String, Integer> m = Collections.synchronizedMap(new HashMap<>());
synchronized (m) { // if you don't write this, there is a risk of CME
for (var e : m.entrySet()) { ... }
}
In ConcurrentHashMap the iterator never throws a ConcurrentModificationException. It is "weakly consistent": during iteration it may or may not see changes.
The atomicity difference is the most important one:
// wrong: two threads can both see "missing" at the same time
if (!map.containsKey(k)) map.put(k, load(k));
// correct
map.computeIfAbsent(k, this::load);
When you might still need synchronizedMap: if you have to wrap an ordered map like TreeMap, or if null values must be stored. If you need both ordering and concurrency, use ConcurrentSkipListMap.
Note: under load, ConcurrentHashMap.size() can be an approximate value, so don't base business decisions on it.
Sign up to mark studied questions and save your progress.