English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

The Difference Between Concurrent Hash Map and Synchronized Hash Map in Java

Concurrent Hashmap is in jdk1.5Introducing the class. The concurrent hash map applies locks at the bucket level called segments only when adding or updating the map. Therefore, the concurrent hash map allows concurrent read and write operations on the map. 

The synchronized hashmap (Collection.syncronizedHashMap()) is a method in the Collection framework. This method applies a lock to the entire collection. Therefore, if one thread is accessing the map, no other thread can access the same map. 

Serial numberKeyConcurrent hash mapSynchronized hash map
1
Implementation
It is a class that implements the concurrent hash map and serializable interface. 
It is a method in the Collection class.  
2
Lock mechanism
Lock part
Lock the entire map. 
3
Performance
Concurrent hash maps allow concurrent read and write operations. Therefore, the performance is better than that of synchronized maps. 
Multiple threads cannot access the map simultaneously. Therefore, the performance is relatively lower than that of concurrent hash maps.
4
Empty key
It does not allow null to be used as a key or value. 
It allows null as a key.
5 
Concurrent modification exception
It does not cause a concurrent modification exception. 
The iterator returned by the synchronized map causes a concurrent modification exception

SynchronizedMap example

public class SynchronizedMapExample {
   public static void main(String[] args) {
      Map<Integer,String> laptopmap = new HashMap<Integer,String>();
      laptopmap.put("1,"IBM");
      laptopmap.put("2,"Dell");
      laptopmap.put("3,"HCL");
      //Create a synchronized map
      Map<Integer,String> syncmap = Collections.synchronizedMap(laptopmap);
      System.out.println("Synchronized map is: "+syncmap);
   }
}

ConcurrentHashMap---example

public class ConcurrentHashMap---Example {
   public static void main(String[] args) {
      //ConcurrentHashMap---
      Map<Integer,String> laptopmap = new ConcurrentHashMap---<Integer,String>();
      laptopmap.put("1,"IBM");
      laptopmap.put("2,"Dell");
      laptopmap.put("3,"HCL");
      System.out.println("ConcurrentHashMap--- is: "+laptopmap);
   }
}