Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Getting Synchronized Map from Java HashMap

  • Last Updated : 13 Jan, 2021

HashMap is a non synchronized collection class. If we want to perform thread-safe operations on it then we must have to synchronize it explicitly. In order to synchronize it explicitly the synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map.

// Get synchronized map using Collections.synchronizedMap()

Map<Integer, String> synchrMap = Collections.synchronizedMap(hmap);

To iterate the synchronized map we use a synchronized block:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

// Synchronized block
synchronized (synchrMap) {

      // Iterate synchronized map
      for (Map.Entry<Integer, String> entry : synchrMap.entrySet()) {

        // Print key : value
        System.out.println(entry.getKey() + " : " + entry.getValue());
        
      }
}

Implementation:

Java




// Java Program to demonstrate how 
// to get synchronized map from HashMap
  
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // New HashMap
        HashMap<Integer, String> hmap = new HashMap<>();
  
        // Add element to map
        hmap.put(1, "Akshay");
        hmap.put(2, "Bina");
        hmap.put(3, "Chintu");
  
        // Get synchronized map using
        // Collections.synchronizedMap()
        Map<Integer, String> synchrMap = Collections.synchronizedMap(hmap);
  
        System.out.println("Synchronized Map : ");
  
        // Synchronized block
        synchronized (synchrMap)
        {
  
            // Iterate synchronized map
            for (Map.Entry<Integer, String> entry :
                 synchrMap.entrySet()) {
  
                // Print key : value
                System.out.println(entry.getKey() + " : "
                                   + entry.getValue());
            }
        }
    }
}
Output
Synchronized Map : 
1 : Akshay
2 : Bina
3 : Chintu



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!