Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Getting Synchronized Map from Java HashMap

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:

// 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
Last Updated : 13 Jan, 2021
Like Article
Save Article
Similar Reads
Related Tutorials