Getting Synchronized Map from Java TreeMap
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
// Java program to demonstrate // synchronization of TreeMap // Importing all classes from // java.util package import java.util.*; // Class public class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check if any exception occurs try { // Step1: Creating a TreeMap object // Declaring object of string type TreeMap<String, String> treeMap = new TreeMap<String, String>(); // Step2: Adding elements into the above Map // Custom inputs treeMap.put( "1" , "Welcome" ); treeMap.put( "2" , "To" ); treeMap.put( "3" , "Beginner" ); treeMap.put( "4" , "For" ); treeMap.put( "5" , "Beginner" ); // Printing all elements of the above Map object System.out.println( "Map : " + treeMap); // Synchronizing the map using // synchronizedMap() method of Collection class Map<String, String> sMap = Collections.synchronizedMap(treeMap); // Printing the Collection System.out.println( "Synchronized map is : " + sMap); } // Catch block to handle the exceptions catch (IllegalArgumentException e) { // Displaying and printing the exception System.out.println( "Exception thrown : " + e); } } } |
Map : {1=Welcome, 2=To, 3=Beginner, 4=For, 5=Beginner} Synchronized map is : {1=Welcome, 2=To, 3=Beginner, 4=For, 5=Beginner}