Getting Synchronized Map from Java HashMap
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



Please Login to comment...