Getting Synchronized Map from Java TreeMap
Last Updated :
27 Jul, 2021
TreeMap is a part of the Java Collections framework. Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains only unique elements. It cannot have a null key but can have multiple null values. TreeMap maintains the ascending order of the elements. Synchronization means controlling the access of multiple threads to any shared resource. A synchronized resource can be accessed by only one thread at a time. Java TreeMap is not synchronized, we have to synchronize it explicitly in order to use it in a multi–threading environment.
TreeMap can be synchronized using the Collections.synchronizedMap() method. The synchronizedMap() method of the Collections class takes the Map that has to be synchronized as a parameter and returns a thread-safe synchronized Map. The synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map.
Syntax:
public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m)
Parameters: This method takes the map as a parameter to be “wrapped” in a synchronized map.
Return Value: This method returns a synchronized view of the specified map.
Implementation:
Example
Java
import java.util.*;
public class GFG {
public static void main(String[] args) throws Exception
{
try {
TreeMap<String, String> treeMap
= new TreeMap<String, String>();
treeMap.put( "1" , "Welcome" );
treeMap.put( "2" , "To" );
treeMap.put( "3" , "Geeks" );
treeMap.put( "4" , "For" );
treeMap.put( "5" , "Geeks" );
System.out.println( "Map : " + treeMap);
Map<String, String> sMap
= Collections.synchronizedMap(treeMap);
System.out.println( "Synchronized map is : "
+ sMap);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output
Map : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}
Synchronized map is : {1=Welcome, 2=To, 3=Geeks, 4=For, 5=Geeks}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...