ConcurrentHashMap, Hashtable and Synchronized Map in Java

All these three class can be used in the multiple thread environment. Here is a summary of the difference:

  • Hashtable is since Java 1.0. The implementation lock the whole table.
  • Synchronized Map is since Java 1.2 under Collection framework. Please refer to the best practice. You also need to lock the whole map.
  • ConcurrentHashMap is since Java 1.5 and also a member of Collection framework. The map is partitioned into segments based on concurrencyLevel. So each segment can have a lock to improve the performance.

A detail comparison is at:


“This class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value.”

Synchronized Map

“It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:”

Map m = Collections.synchronizedMap(new HashMap());
  Set s = m.keySet();  // Needn't be in synchronized block
  synchronized (m) {  // Synchronizing on m, not s!
      Iterator i = s.iterator(); // Must be in synchronized block
      while (i.hasNext())


“A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do notentail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.”

Always use putIfAbsent instead of following code to achieve atomic action and better performance:

if (!map.containsKey(key))
   return map.put(key, value);
   return map.get(key);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s