skip to content

What is Hashtable, how does it differ from HashMap, and why is it considered a legacy class?

level: juniorimportance: must knowfreq 78%

answer

  1. Map methods share one big lock
  2. No null key, no null value (NPE)
  3. Java 1.0, extends Dictionary, legacy
  4. Replace with HashMap (single) or ConcurrentHashMap (concurrent)
  5. Enumeration not fail-fast; iterator fail-fast

basics

~20 s

Hashtable is an old key-value map whose get, put and similar calls share one lock, so each is thread-safe, and it refuses null keys and null values. HashMap is newer, faster, allows one null key and null values, but is not thread-safe.

solid answer

~50 s

Hashtable is a legacy map from Java 1.0 that stores key-value pairs. Its map methods share the table object's lock, so each call is thread-safe but slow under contention because only one thread can run them at a time; iterators and Enumerations take no lock. It rejects null keys and null values, throwing NullPointerException. HashMap (Java 1.2) is the modern replacement: not synchronized, faster, and it permits one null key plus null values. Both compute a bucket from the key's hashCode and resolve collisions, and both implement Map, but Hashtable also extends the obsolete Dictionary class and its Enumerations are not fail-fast: changing the table during one gives undefined results, while its iterators are fail-fast. For single-threaded code use HashMap; for concurrent code prefer ConcurrentHashMap, which locks only parts of the table and scales far better than Hashtable's whole-object lock. Legacy means superseded here: Hashtable is not deprecated.

code

java · 11 lines
java
Hashtable<String, String> ht = new Hashtable<>();
ht.put("a", "1");           // ok
// ht.put(null, "x");       // throws NullPointerException
// ht.put("k", null);       // throws NullPointerException

HashMap<String, String> hm = new HashMap<>();
hm.put(null, null);          // perfectly fine in HashMap

// Prefer this for concurrency, not Hashtable:
ConcurrentHashMap<String, String> chm = new ConcurrentHashMap<>();
chm.put("a", "1");

go deeper

for a junior

Knows Hashtable is thread-safe, rejects nulls, and that HashMap is the usual modern choice.

for a middle

Explains the single synchronized lock mechanism, the null-handling difference, and recommends ConcurrentHashMap for concurrency.

for a senior

Discusses contention cost of the whole-object lock vs ConcurrentHashMap's partitioned locking, fail-fast iterators vs not-fail-fast Enumerations, and the Dictionary legacy lineage.

for a principal

Frames Hashtable as a cautionary design (coarse locking), reasons about when synchronizedMap vs ConcurrentHashMap is appropriate, memory-visibility guarantees, and migration strategy for legacy codebases.

## What a Map is A **Map** is a data structure that stores **key-value pairs**: you give it a key (like a word) and it gives you back a value (like that word's definition). Each key appears at most once. Java's `java.util.Map` interface defines this contract (`put`, `get`, `remove`, etc.). ## What hashing means here Most maps are **hash-based**: when you `put(key, value)`, the map calls `key.hashCode()` to get an integer, then maps that integer to a slot (a **bucket**) in an internal array. `get(key)` repeats the calculation to jump straight to the right bucket. When two keys land in the same bucket (a **collision**), the entries are chained together and compared with `equals()`. This is what makes `get`/`put` average **O(1)** (constant time). ## Hashtable `Hashtable` is one of Java's original classes (Java 1.0). It is a hash-based map with two defining traits: 1. **Its map methods share one lock.** Nearly every public method is declared `synchronized`, and the other public ones (`containsValue`, `keySet`, `entrySet`, `values`) call a synchronized method or return a view synchronized on the table. `synchronized` means the JVM forces a thread to acquire a lock (the table object's monitor) before running the method, and only one thread can hold that lock at a time. So each single map call is **thread-safe**: multiple threads can make them without corrupting the table. A sequence of calls is not one atomic step. Iterators, `Enumeration`s and `Entry.setValue` take no lock at all, so iterating needs your own `synchronized (table)` block, because another thread's `put` can fail the iterator. The cost is **contention** — even `get` must wait its turn, so it does not scale on multi-core machines. 2. **It forbids `null`.** Its contract accepts any non-null object as a key or value, and passing a null key or null value throws `NullPointerException`: `put` checks the value explicitly, then calls `key.hashCode()` on the key. One consequence is that a null from `get` can only mean the key is absent. `Hashtable` also extends `Dictionary`, whose own Javadoc calls it obsolete, and predates the Collections Framework: it was retrofitted to implement `Map` in 1.2, so it carries `Enumeration`-based traversal as well as the modern `Iterator`. ## HashMap — the modern replacement `HashMap` (Java 1.2, part of the Collections Framework) is the everyday map. Differences: | | Hashtable | HashMap | |---|---|---| | Thread-safe | Per call (one lock on map methods) | No | | null key | No (NPE) | One allowed | | null values | No (NPE) | Allowed | | Speed (single thread) | Slower (lock overhead) | Faster | | Legacy / Dictionary | Yes | No | | Traversal | Enumeration (not fail-fast) + Iterator (fail-fast) | Iterator (fail-fast) | | Default capacity, indexing | 11, `(hash & 0x7FFFFFFF) % length` | 16, `(n - 1) & hash` | | Collision bins | Linked lists only | Lists that can become trees | **Fail-fast** means an iterator throws `ConcurrentModificationException` if the map is structurally changed while you iterate (it detects this via a modification counter, on a best-effort basis, so it only serves to detect bugs). Hashtable's older `Enumeration` does **not** do this, and that does not make it safe: the Javadoc says the results of enumerating a table modified meanwhile are undefined, so calling it "fail-safe" is wrong. ## What to use instead - **Single-threaded:** use `HashMap`. - **Concurrent:** the Javadoc recommends `ConcurrentHashMap` in place of `Hashtable` for highly concurrent use. It partitions the table and locks only small portions (or uses lock-free reads), so many threads proceed in parallel. It rejects null too, so that rule survives a migration. If you genuinely need a fully-synchronized `HashMap`, wrap it with `Collections.synchronizedMap(new HashMap<>())` — but that still has one big lock, like Hashtable. ## Why "legacy" `Hashtable` is superseded, not removed: at JDK 27, as at 25 LTS, it carries no `@Deprecated`, and `java.util.Properties` still extends it. Its whole-object lock is a poor concurrency design, and its null prohibition is a frequent surprise. Modern code uses `HashMap` or `ConcurrentHashMap`. Two later JDK changes touched that one lock, and neither makes it scale: - **Java 15** turned biased locking off by default, and its release notes name `Hashtable` and `Vector` as APIs whose uncontended synchronization that might affect. - **Java 24** (JEP 491) lets a virtual thread that blocks in `synchronized` release its carrier, so `Hashtable`'s monitor no longer pins one.

  • Why does Hashtable reject null keys and values while HashMap allows them?
    Hashtable's contract accepts only non-null keys and values: put rejects a null value explicitly and calls hashCode() directly on the key, so get returning null can only mean absent. HashMap handles a null key specially (bucket 0), and because null can also be a stored value, containsKey() is what tells the two cases apart.
  • If I need a thread-safe map today, what should I use instead of Hashtable?
    ConcurrentHashMap, which uses fine-grained locking / lock-free reads and scales across cores. Collections.synchronizedMap is an option but uses a single lock like Hashtable, so it does not scale better.

Hashtable is a shop with one cashier and a rule that turns away anyone without a name tag (no nulls). HashMap drops the cashier (faster, but no theft protection); ConcurrentHashMap opens many checkout lanes (scales).

  • Saying Hashtable allows a null key like HashMap does (it throws NPE).
  • Claiming Hashtable is a good choice for modern concurrent code (use ConcurrentHashMap).
  • Thinking 'synchronized methods' means it scales well under many threads — it serializes those calls.
  • Calling Hashtable's Enumeration fail-safe; it is only not fail-fast, and its results are undefined under modification.
  • Calling Hashtable deprecated; it is legacy in practice but carries no @Deprecated.

Hashtable
Java 1.0
HashMap
Java 1.2
ConcurrentHashMap
Java 1.5

Assumes JDK 27; Hashtable.java is byte-identical at JDK 25, so 25 LTS behaves the same. Biased locking went off by default in Java 15 and virtual threads stopped pinning on synchronized in Java 24, both before either release.

context