Which is true about HashMap, Hashtable and ConcurrentHashMap?
Options
- All three are equally safe and fast when many threads use them
HashMapis unsafe;Hashtablelocks all;ConcurrentHashMapis finer (Correct option)HashMapis the only one that allows null keys, and it is thread-safeConcurrentHashMapis always slower thanHashtablein every case
Answer
HashMap is not thread-safe; Hashtable locks the whole map (old, slow); ConcurrentHashMap allows many threads with fine-grained locking
Why
HashMap is fast but unsafe if several threads modify it at the same time (lost updates, even infinite loops in old versions).
Hashtable is synchronized on every method, so only one thread works at a time. It is legacy; avoid it.
ConcurrentHashMap is designed for concurrency: reads do not block and writes lock only small parts. It also offers atomic operations like computeIfAbsent and merge. It does not allow null keys or values.
Remember
Shared map between threads: ConcurrentHashMap.