Video in progress

What do you choose instead of HashMap where several threads are involved, and why?

ConcurrentHashMap. HashMap is not thread-safe: with parallel writes, data is lost or the structure gets corrupted. Collections.synchronizedMap works, but it makes everything sequential with a single lock.

📖 Answer

Let's compare the three options:

  • HashMap: if two threads put at the same time, entries can be lost; during a resize, get returns a wrong result. In Java 7 and older it could even end up in an infinite loop.
  • Collections.synchronizedMap(new HashMap<>()): every method takes one shared lock. Correct, but a bottleneck with many threads. During iteration you also have to do synchronized (map) by hand.
  • ConcurrentHashMap: reads are almost lock-free, and writes block only the relevant bucket.
ConcurrentHashMap<String, Integer> hits = new ConcurrentHashMap<>();

hits.merge(url, 1, Integer::sum);            // atomic increment
hits.computeIfAbsent(key, k -> loadValue(k)); // compute once

A trap: if (!map.containsKey(k)) map.put(k, v) is a race in a ConcurrentHashMap too. Use the atomic methods: putIfAbsent, compute, merge.

One more difference: ConcurrentHashMap accepts neither a null key nor a null value.