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:
// 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
import java.util.*;
class GFG {
public static void main(String[] args)
{
HashMap<Integer, String> hmap = new HashMap<>();
hmap.put( 1 , "Akshay" );
hmap.put( 2 , "Bina" );
hmap.put( 3 , "Chintu" );
Map<Integer, String> synchrMap = Collections.synchronizedMap(hmap);
System.out.println( "Synchronized Map : " );
synchronized (synchrMap)
{
for (Map.Entry<Integer, String> entry :
synchrMap.entrySet()) {
System.out.println(entry.getKey() + " : "
+ entry.getValue());
}
}
}
}
|
Output
Synchronized Map :
1 : Akshay
2 : Bina
3 : Chintu
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...