Course contentsShow
← Java
Lesson 1156 of 2,87026. Map ImplementationsFree lesson

Thread Safety: Hashtable vs Collections.synchronizedMap

Compare Hashtable with synchronized wrappers and understand when each approach is appropriate.

Thread Safety: Hashtable vs Collections.synchronizedMap

What you'll learn: You'll understand the difference between Hashtable's built-in synchronization and Collections.synchronizedMap, and when to use each approach.

Two Approaches to Thread-Safe Maps

Both Hashtable and Collections.synchronizedMap provide thread-safe map implementations, but they achieve it differently.

Hashtable has synchronization baked directly into its methods. Every operation (put, get, remove, etc.) is inherently synchronized, meaning only one thread can access the map at a time.

Collections.synchronizedMap is a wrapper that takes any Map implementation and adds synchronization around it. You pass in a HashMap (or TreeMap, LinkedHashMap), and it returns a synchronized version.

Think of It Like Building Security

Imagine a building with valuables inside:

  • Hashtable is like a building constructed with built-in vault walls—security is part of the structure itself.
  • Collections.synchronizedMap is like hiring security guards to wrap around an existing building—you add protection externally.

When to Use Which

Use Collections.synchronizedMap when:

  • You need flexibility (want sorted maps, insertion-order maps, etc.)
  • You're already using HashMap and need to make it thread-safe
  • You want to choose the underlying implementation

Use Hashtable when:

  • You're maintaining legacy code (it's the older approach)
  • Actually... modern Java rarely needs Hashtable at all

The Modern Reality

In contemporary Java, you typically use Collections.synchronizedMap for simple thread safety or ConcurrentHashMap for better performance (though that's beyond your current scope). Hashtable remains mainly for backward compatibility.

Key Takeaway: Both Hashtable and Collections.synchronizedMap provide thread-safe maps, but Collections.synchronizedMap offers more flexibility by wrapping any Map implementation, making it the preferred choice in modern Java.