Java Collections - synchronizedMap() Method
The java.util.Collections.synchronizedMap() method returns a synchronized (thread-safe) map backed by the specified map.
Syntax
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
Here, K and V are the type of key and value respectively maintained by the map.
Parameters
m |
Specify the map to be "wrapped" in a synchronized map. |
Return Value
Returns a synchronized view of the specified map.
Exception
NA.
Example:
In the example below, the java.util.Collections.synchronizedMap() method returns a synchronized view of the given map.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a Map object Map<Integer, String> MyMap = new HashMap<Integer, String>(); //populating MyMap MyMap.put(101, "John"); MyMap.put(102, "Marry"); MyMap.put(103, "Kim"); //printing the map System.out.println("MyMap contains: " + MyMap); //creating an synchronized view of the map Map NewMap = Collections.synchronizedMap(MyMap); //printing the synchronized map System.out.println("NewMap contains: " + NewMap); } }
The output of the above code will be:
MyMap contains: {101=John, 102=Marry, 103=Kim} NewMap contains: {101=John, 102=Marry, 103=Kim}
❮ Java.util - Collections