Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Java
Javamedium

HashMap vs ConcurrentHashMap — what’s the practical difference?

Tags
#hashmap#concurrency#concurrenthashmap
Back to categoryPractice quiz

Answer

`HashMap` is not thread-safe; concurrent writes can corrupt it. `ConcurrentHashMap` supports safe concurrent access with good performance (and disallows null keys/values). Use it when multiple threads read/write without external locking.

Advanced answer

Deep dive

`HashMap` has no concurrency guarantees. Concurrent writes can lead to lost updates and even internal corruption.

`ConcurrentHashMap` is designed for high concurrency:

  • Updates use fine-grained synchronization/CAS on bins.
  • Iterators are weakly consistent (they don’t throw ConcurrentModificationException and may not see all updates).
  • It disallows null keys/values (null would be ambiguous for “missing”).

Practical guidance

  • Many threads, reads + writes: use `ConcurrentHashMap`.
  • You still need atomic operations for compound actions (check-then-act): prefer `computeIfAbsent`, `merge`, `compute`.

Common pitfalls

  • Thinking it makes *your whole algorithm* thread-safe.
  • Using `get()` then `put()` as if it were atomic.
  • Putting nulls (not allowed).

Related questions

Java
HashMap vs ConcurrentHashMap: when should you use each?
#java#collections#concurrency
Java
`synchronized` vs `ReentrantLock`: what are the differences?
#java#concurrency#locks
Java
Parallel streams: when can they help and what are common pitfalls?
#java#streams#parallel
Java
`synchronized` vs `ReentrantLock` - when would you choose one?
#concurrency#locks#synchronized
Java
What does `ThreadLocal` do and what is a common pitfall?
#threadlocal#concurrency#thread-pool
Java
Java Memory Model: what does “happens-before” mean (in simple terms)?
#jmm#happens-before#concurrency