How to Synchronize HashMap in Java with Example

HashMap is not synchronized collection class. We need to synchronize explicitly in order to perform thread-safe operations on it.In the last tutorial we have seen different ways to loop HashMap in java.
In this tutorial we will see how to synchronize HashMap.

Program to Synchronize HashMap in Java with Example

In this program we have a HashMap of integer keys and String values.
According to  Oracle docs, in order to synchronize HashMap we need to use Collections.synchronizedMap(hashmap). It returns a thread safe map backed up by the specified HashMap.Other important point to note that iterator should be used in a synchronized block even if we have synchronized the HashMap explicitly.

import java.util.*;

 public class HashMapSynchronizeExample {
    public static void main(String args[]) {
    // Creating a HashMap of Integer keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
    hashmap.put(1, "Value1");
    hashmap.put(2, "Value2");
    hashmap.put(3, "Value3");
    hashmap.put(4, "Value4");
    hashmap.put(5, "Value5");
    Map map= Collections.synchronizedMap(hashmap);
    Set set = map.entrySet();
        Iterator i = set.iterator();
        // Display elements
        while(i.hasNext()) {
            Map.Entry pair = (Map.Entry);
            System.out.print(pair.getKey() + ": ");

1: Value1
2: Value2
3: Value3
4: Value4
5: Value5

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry