Synchronize HashMap in Java with an example

In this tutorial, we will learn about How to Synchronize HashMap in Java ?

HashMap is one of the most used collections in Java. HashMap is an Hash table based implementation of the Map interface. We all know that HashMap is not a synchronized class. When we use HashMap in multithreading environment, it may be possible that each thread is either adding, updating or removing the records/entries. In this case it will create problem and HashMap will not behave as expected.

To resolve this problem, we can synchronize HashMap in Java. Snchronization of HashMap will affect the performance and probably reduce the speed of HashMap as synchronized method is always slower than non-synchronized one.

Let’s see how to Synchronize HashMap in Java with an example.

Let’s take a HashMap with String keys and String type values. In order to synchronize a HashMap we need to use Collections.synchronizedMap(new HashMap()). This returns a thread-safe Map which is backed by HashMap.

Synchronized HashMap:

Let’s create SynchronizedHashMap.java class.

Output:

 

Related posts

Leave a Comment