Hashtable

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Hashtable is a legacy class from Java 1.0 that implements a key-value map.
  • It is fully synchronized (thread-safe), but at a high performance cost.
  • It does not allow null keys or null values.
  • Best Practice: Do not use Hashtable. Use HashMap (for single-threaded) or ConcurrentHashMap (for multi-threaded).

Concept

Like Vector and Stack, Hashtable was part of the original Java release before the Collections Framework. It was retrofitted to implement the Map interface in Java 1.2.

The Problem with Hashtable

To achieve thread safety, Hashtable locks the entire map for every single operation (read or write). If Thread A is reading a value, Thread B is completely blocked from writing or reading any other value. This creates a massive bottleneck in highly concurrent applications.

Examples

import java.util.Hashtable;

public class HashtableExample {
    public static void main(String[] args) {
        Hashtable<String, String> table = new Hashtable<>();
        
        table.put("1", "One");
        table.put("2", "Two");
        
        // Throws NullPointerException immediately
        // table.put(null, "Three"); 
        
        // Throws NullPointerException immediately
        // table.put("3", null); 
        
        System.out.println(table.get("1")); // "One"
    }
}

Interview Questions

Q: What are the main differences between HashMap and Hashtable?
A: 1. Thread Safety: Hashtable is synchronized; HashMap is not.
2. Null Values: HashMap allows one null key and multiple null values. Hashtable allows neither; attempting to insert null throws a NullPointerException.
3. Performance: Because of the global lock, Hashtable is much slower than HashMap in single-threaded environments, and much slower than ConcurrentHashMap in multi-threaded environments.

Q: Why does Hashtable forbid null keys and values?
A: It was an early design decision by the Java creators. To implement the get(key) method safely in a multithreaded environment without returning ambiguous results, they decided to reject null entirely. If get(key) returns null in a Hashtable, you know 100% that the key does not exist. In a HashMap, returning null could mean the key doesn’t exist, OR it could mean the key exists but its value was explicitly set to null.