Mid-level (2-5 years)Java

What is the difference between HashMap, Hashtable and ConcurrentHashMap in Java?

Quick answer

HashMap is not thread-safe, Hashtable is thread-safe by locking the whole map on every method, and ConcurrentHashMap is thread-safe with much finer-grained locking and lock-free reads, so it scales far better.

Using a plain HashMap from several threads can lose updates or, in older versions, even loop forever during a resize. Hashtable and Collections.synchronizedMap() fix this by synchronising every operation on a single lock, so threads queue up behind each other.

ConcurrentHashMap locks only the bucket being modified (using CAS and synchronized on the bucket head since Java 8) and allows reads without locking, so many threads can work in parallel. It does not allow null keys or values. Its compound atomic methods such as computeIfAbsent, merge and putIfAbsent should be used instead of a separate get followed by put, which is a race condition.

ConcurrentHashMap<String, Integer> hits = new ConcurrentHashMap<>();
hits.merge("home", 1, Integer::sum);   // atomic increment

// racy even on a ConcurrentHashMap:
// if (!map.containsKey(k)) map.put(k, v);