Concurrent collections question 76 of 180 senior
When is a plain HashMap behind your own lock better than ConcurrentHashMap?
- Never
- Correct: When you need several operations to be atomic together, which a concurrent map cannot give you across calls
- When the map is large
- When there is only one thread
ConcurrentHashMap gives per-operation atomicity plus a handful of compound operations. If your
invariant spans two maps, or a map and a counter, or requires iterating and then updating based on what
you saw, no amount of concurrent collection will help: the state between your calls is unprotected.
In that case a HashMap guarded by a ReentrantLock you hold across the whole operation is both
simpler and more correct, and the honest answer in an interview. The follow-up is usually about scope:
keep the lock as narrow as the invariant, and never call unknown code (a listener, a callback) while
holding it.
Quiz yourself on Concurrent collections Suggest a correction