Java · OOP, JVM and backend craft
How does ConcurrentHashMap achieve thread safety?
Short answer
ConcurrentHashMap allows concurrent reads and writes without locking the whole table. It uses CAS and per-bin synchronization, forbids null keys and values, and provides atomic compound operations.
Reads are largely lock-free because nodes are published safely and the table is traversed with volatile reads. Writes use compare-and-swap for empty bins and synchronize on the first node of an occupied bin. Different bins can be updated in parallel, so contention is limited to the same bucket.
ConcurrentHashMap<String, Long> counters = new ConcurrentHashMap<>();
counters.merge("requests", 1L, Long::sum);
counters.computeIfAbsent("errors", key -> 0L);Properties that matter in production
- Null keys and values are rejected, so a null result is unambiguous
- Iterators are weakly consistent and never throw ConcurrentModificationException
- size and isEmpty are estimates under concurrent updates
- Compound actions must use the atomic methods rather than separate get and put calls
Do not wrap a ConcurrentHashMap in Collections.synchronizedMap, because that reintroduces a global lock. Also do not treat size as exact for coordination. If you need an exact snapshot, quiesce writers or use a different structure.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does ConcurrentHashMap forbid null values?
- 2What does weakly consistent iteration mean?
- 3Why is get followed by put still a race?
- 4When would you prefer a synchronized map?
Say it in the interview
ConcurrentHashMap avoids a single global lock. Reads are mostly lock-free, and writes use CAS for empty bins or synchronize on the bin head for occupied ones, so updates to different buckets proceed in parallel. It rejects null keys and values, and iterators are weakly consistent rather than fail-fast. For compound updates I use merge, compute or computeIfAbsent, because a separate get and put is still a race.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.