Repaso
EspaƱol
Java CoreIntermediateJV-25

Which is true about HashMap, Hashtable and ConcurrentHashMap?

Options

  1. All three are equally safe and fast when many threads use them
  2. HashMap is unsafe; Hashtable locks all; ConcurrentHashMap is finer (Correct option)
  3. HashMap is the only one that allows null keys, and it is thread-safe
  4. ConcurrentHashMap is always slower than Hashtable in 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.

Key terms

Practice this question in Repaso