Interview Q&A · Java · 4 questions in this topic

Hashtable, HashMap and ConcurrentHashMap — Java Interview Q&A

All Java topics

Legacy Hashtable versus modern HashMap and ConcurrentHashMap, and how concurrent maps achieve thread safety. Part of Collections Framework · 294 questions in the Java bank.

What is Hashtable?

Answer

Hashtable is a legacy synchronized map from Java 1.0 that was retrofitted to implement Map. It originally extended the obsolete Dictionary class, which is why old tutorials still mention that hierarchy. It forbids both null keys and null values and throws NullPointerException if you try to store them. It is largely replaced by HashMap for single-threaded use and by ConcurrentHashMap for concurrent use.

HashMap vs Hashtable?

Answer

HashMap and Hashtable share the key-value model but differ in age, locking, and null policy. HashMap is an unsynchronized modern Collections Framework class, while Hashtable is a synchronized legacy class. HashMap permits one null key and any number of null values, while Hashtable forbids all nulls. For single-threaded code HashMap is faster, and for concurrent code neither raw Hashtable nor externally synchronized HashMap scales as well as ConcurrentHashMap.

Key points

  1. 1Synchronization: unsynchronized versus synchronized on every method.
  2. 2Nulls: one null key and many null values allowed versus no nulls allowed.
  3. 3Performance: faster single-threaded lookup versus lock overhead on every call.
  4. 4Status: modern default versus legacy class kept for old APIs.

What is ConcurrentHashMap?

Answer

ConcurrentHashMap is a thread-safe map in java.util.concurrent built for high-concurrency use. Since Java 8 it avoids global locking and segment locks entirely, using compare-and-swap steps plus locks on individual bins where needed. Like Hashtable it forbids null keys and null values, partly so that a null return unambiguously means absence under concurrency. Its iterators are weakly consistent rather than fail-fast, so they keep traversing during concurrent updates without throwing ConcurrentModificationException.

💡 Older books say segments lock the map, but Java 8 replaced segments with CAS plus per-bin locking.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits