Hashtable in Java

Hashtable is a legacy thread-safe Map from Java 1.0 that synchronizes every method, forbids null keys and values, and should not be used in new code.

Hashtable<K, V> is one of the original collection classes in Java, available since JDK 1.0. It stores key-value pairs in a hash table and synchronizes every public method, making it thread-safe out of the box. However, this coarse-grained locking makes it significantly slower than HashMap in single-threaded contexts and less scalable than ConcurrentHashMap in multithreaded ones. Hashtable is considered legacy and should not be used in new code — but it appears frequently in interview questions and in older codebases, so you must understand it.

How Hashtable Works

Hashtable uses the same hash-table bucket model as HashMap (before Java 8 improvements). Key differences:

  • Every method (put, get, remove, size, containsKey, etc.) is synchronized on this.
  • Neither null keys nor null values are allowed; passing either throws NullPointerException.
  • Default initial capacity is 11 (not a power of two, unlike HashMap's 16).
  • Default load factor is 0.75; rehash doubles the capacity and adds 1.
  • Does not benefit from Java 8's treeification of buckets.
Property Hashtable HashMap ConcurrentHashMap
Thread-safe Yes (full sync) No Yes (fine-grained)
Null keys No One allowed No
Null values No Allowed No
Iteration order Undefined Undefined Undefined
Performance (single-thread) Slower (lock overhead) Fastest Slightly slower than HashMap
Performance (multi-thread) Poor (single lock) Unsafe Best
Recommended for new code No Yes (single-thread) Yes (multi-thread)

Examples

Basic Hashtable usage (for reference)

import java.util.Hashtable;
import java.util.Map;

public class HashtableBasics {
    public static void main(String[] args) {
        // Note: prefer HashMap or ConcurrentHashMap in new code
        Map<String, Integer> table = new Hashtable<>();
        table.put("alpha", 1);
        table.put("beta", 2);
        table.put("gamma", 3);

        System.out.println(table.get("alpha")); // 1
        System.out.println(table.containsKey("delta")); // false
        System.out.println(table.size()); // 3

        table.remove("beta");
        System.out.println(table); // {gamma=3, alpha=1}  — order varies

        // This would throw NullPointerException:
        // table.put(null, 4);
        // table.put("key", null);
    }
}

Migrating from Hashtable to ConcurrentHashMap

import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MigrateFromHashtable {
    // Old code — do not use in new projects
    private static final Hashtable<String, String> legacyCache = new Hashtable<>();

    // New equivalent — prefer this
    private static final ConcurrentHashMap<String, String> modernCache = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        // ConcurrentHashMap is a drop-in replacement for most Hashtable use cases
        modernCache.put("user:1", "Alice");
        modernCache.put("user:2", "Bob");

        // putIfAbsent is atomic — not available in Hashtable
        modernCache.putIfAbsent("user:1", "Should not replace Alice");
        System.out.println(modernCache.get("user:1")); // Alice

        // computeIfAbsent for lazy loading — also not in Hashtable
        modernCache.computeIfAbsent("user:3", k -> "Charlie");
        System.out.println(modernCache.get("user:3")); // Charlie
    }
}

Common Mistakes

  1. Using Hashtable in new code. The Java documentation explicitly states that Hashtable has been retrofitted to implement Map and should be replaced by HashMap (single-threaded) or ConcurrentHashMap (multi-threaded). There is no reason to use Hashtable in code written after Java 2.

  2. Inserting null keys or values. Unlike HashMap, Hashtable throws NullPointerException for both null keys and null values at the time of insertion — not lazily. This is a common source of surprises when migrating code from HashMap to Hashtable.

  3. Assuming synchronized means fully concurrent. Every Hashtable method holds the lock for its entire duration. Compound operations like "check then put" are still not atomic without external synchronization. ConcurrentHashMap provides atomic compound methods (computeIfAbsent, putIfAbsent, merge) that Hashtable does not.

  4. Using the legacy contains(value) method. Hashtable has a contains(value) method (equivalent to containsValue) that is confusing because it tests a value, not a key. In HashMap there is only containsValue and containsKey. Calling contains on Hashtable with a key argument silently checks values instead.

  5. Iterating while relying on full synchronization. Even though all methods are synchronized, iterating over a Hashtable with an Enumeration (the older elements() / keys() methods) or the fail-fast Iterator from entrySet() is not protected by the method-level locks. You still need external synchronization to safely iterate.

Best Practices

  • Do not use Hashtable in new code — use ConcurrentHashMap for thread safety or HashMap for single-threaded use.
  • When maintaining legacy code, replace Hashtable with ConcurrentHashMap incrementally; the API is largely compatible but does not permit null.
  • Use ConcurrentHashMap's atomic methods (computeIfAbsent, putIfAbsent, merge) instead of manual synchronized blocks.
  • If you must interoperate with a Hashtable field, consider wrapping it: Map<K,V> safe = Collections.synchronizedMap(new HashMap<>()) is semantically equivalent.
  • When benchmarking legacy code, remember that every Hashtable call acquires a monitor lock — even size() — which incurs significant overhead in high-throughput scenarios.

Interview Questions

1. What is Hashtable and why is it considered legacy?

Hashtable is a Java 1.0-era Map implementation with fully synchronized methods. It is considered legacy because HashMap (faster, single-threaded) and ConcurrentHashMap (scalable, multi-threaded) provide better alternatives for every use case. The Java docs recommend using HashMap or ConcurrentHashMap instead.

2. How does Hashtable differ from HashMap?

The main differences: Hashtable synchronizes every method (slower); HashMap is unsynchronized (faster). Hashtable does not permit null keys or values; HashMap permits one null key and many null values. Hashtable uses an initial capacity of 11; HashMap uses 16. HashMap benefits from Java 8 treeification; Hashtable does not.

3. How does Hashtable differ from ConcurrentHashMap?

Hashtable uses a single lock on this for every operation — only one thread can access it at a time. ConcurrentHashMap (Java 8+) uses CAS (compare-and-swap) for most reads and fine-grained synchronized blocks on individual bin heads for writes, allowing multiple threads to operate on different segments simultaneously. ConcurrentHashMap also provides atomic compound operations; Hashtable does not.

4. Why does Hashtable not allow null keys or values?

This was a design decision in Java 1.0. The original contains(value) method could not distinguish between "value is null" and "key not present" if null values were allowed. HashMap works around this with the explicit containsKey / containsValue split. ConcurrentHashMap also forbids null to avoid ambiguity in concurrent lookups.

5. Is Hashtable fail-fast?

The Enumeration returned by Hashtable.keys() and Hashtable.elements() is not fail-fast. However, the Iterator returned via entrySet().iterator() (added when Hashtable was retrofitted to implement Map) is fail-fast and throws ConcurrentModificationException on concurrent structural modification.

6. Can you use Hashtable as a drop-in replacement for HashMap?

Mostly yes, with two caveats: Hashtable rejects null keys and values (which HashMap accepts), and all methods are synchronized. Code that inserts null into a HashMap will throw NullPointerException on Hashtable. The ConcurrentHashMap is generally the correct drop-in replacement when thread safety is needed.

7. When would you ever encounter Hashtable in a modern codebase?

In legacy enterprise codebases (pre-Java 5), in Android's earlier APIs, and in third-party libraries that were written before ConcurrentHashMap existed. You may also encounter it in properties-related APIs: java.util.Properties extends Hashtable<Object, Object>.

Summary

  • Hashtable is a legacy, fully-synchronized hash-map from Java 1.0; do not use it in new code.
  • It forbids null keys and null values; inserting either throws NullPointerException.
  • Every method acquires a single lock on this, limiting scalability to one thread at a time.
  • Prefer HashMap for single-threaded use and ConcurrentHashMap for concurrent use.
  • Understanding Hashtable is important for maintaining legacy code and for answering interview comparison questions.

Continue Learning

Previous: TreeMap | Next: ConcurrentHashMap

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.