Java ConcurrentHashMap vs Collections.synchronizedMap()

Java HashMap is not synchronized by default. If we add/remove key-value pairs from a HashMap in a concurrent application where multiple threads add and remove pairs, we may have an inconsistent map state. Learn to synchronize a HashMap and difference with ConcurrentHashMap in Java.

1. ConcurrentHashMap Class

Our first choice should always be using the ConcurrentHashMap class if we wish to use a Map in a concurrent environment. ConcurrentHashMap support concurrent access to its key-value pairs by design. We do not need to perform any additional code modifications to enable synchronization on the map.

Please note that Iterator obtained from ConcurrentHashMap does not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time. It means each iterator we obtain from a ConcurrentHashMap is designed to be used by a single thread and should not be passed around.

If we do so, there is no guarantee that one thread will see the changes to the map that the other thread performs (without obtaining a new iterator from the map). The iterator is guaranteed to reflect the state of the map at the time of its creation.

Let’s take an example of working with ConcurrentHashMap.

ConcurrentHashMap<Integer, String> concurrHashMap = new ConcurrentHashMap<>();

//Put require no synchronization
concurrHashMap.put(1, "A");
concurrHashMap.put(2, "B");

//Get require no synchronization
concurrHashMap.get(1);

Iterator<Integer> itr = concurrHashMap.keySet().iterator();

//Using synchronized block is advisable
synchronized (concurrHashMap) {
  while (itr.hasNext()) {
    System.out.println(concurrHashMap.get(itr.next()));
  }
}

Program output.

A
B

2. Collections.synchronizedMap()

A synchronized HashMap also works very similar to ConcurrentHashMap, with few differences.

The SynchronizedHashMap allows only one thread to perform read/write operations at a time because all of its methods are declared synchronized. Concurrenthashmap allows multiple threads to work independently on different segments in the map. This allows a higher degree of concurrency in ConcurrentHashMap and thus improves the application’s overall performance.

Iterators from both classes should be used inside synchronized block, but the iterator from SynchronizedHashMap is fail-fast. ConcurrentHashMap iterators are not fail-fast.

Map<Integer, String> syncHashMap = Collections.synchronizedMap(new HashMap<>());

//Put require no synchronization
syncHashMap.put(1, "A");
syncHashMap.put(2, "B");

//Get require no synchronization
syncHashMap.get(1);

Iterator<Integer> iterator = syncHashMap.keySet().iterator();

//Using synchronized block is advisable
synchronized (syncHashMap) {
  while (iterator.hasNext()) {
    System.out.println(syncHashMap.get(iterator.next()));
  }
}

Program output.

A
B

3. Difference between a Synchronized HashMap and ConcurrentHashMap

Let’s identify a few differences between both versions of maps so that we can decide which one to choose in which condition.

  • Multiple threads can add/remove key-value pairs from ConcurrentHashMap, while only one thread can change in the case of SynchronizedHashMap. This results in a higher degree of concurrency in ConcurrentHashMap.
  • No need to lock the map to read a value in ConcurrentHashMap. A retrieval operation will return the value inserted by the most recently completed insert operation. A lock is required for the read operation, too, in SynchronizedHashMap.
  • ConcurrentHashMap does not throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it. The iterator reflects the state of the map at the time of its creation. SynchronizedHashMap returns Iterator, which fails fast on concurrent modification.

4. Conclusion

On the basis of the above arguments, we can conclude that using the ConcurrentHashMap is always a better choice if we have to create a new Map. Use Collections.synchronizedMap() when we have an existing Map instance, and we want to synchronize it.

Drop me your questions related to synchronizing a hashmap in Java.

Happy Learning !!

Read More :
HashMap Java Docs
ConcurrentHashMap Java Docs

Source Code on Github

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial