Video in progress

Strong Junior 🧺 Collections

What is the difference between Hashtable and HashMap, and why is Hashtable called obsolete?

Hashtable / HashMap / ConcurrentHashMap — Thread-safe: yes, one shared lock / no / yes, at the bucket level; null key/value: no / yes / no; Iteration: also has Enumeration / fail-fast iterator / weakly consistent

📖 Answer

Hashtable HashMap ConcurrentHashMap
Thread-safe yes, one shared lock no yes, at the bucket level
null key/value no yes no
Iteration also has Enumeration fail-fast iterator weakly consistent

The problem with Hashtable is a single lock for the whole table. Even if 16 threads only read, they wait in line. On top of that, compound operations like "check, then write" are still not atomic.

ConcurrentHashMap, on the other hand, practically takes no lock on reads, blocks only the relevant bucket on writes, and offers atomic methods such as putIfAbsent, compute and merge.

If you see Hashtable in new code, it is usually tied to an old library or to Properties (which extends Hashtable).