Creating a synchronized map

In this post under Java Collections, I will explain with example how to create synchronized map.

Below is the complete code for your reference

Main class

1  package core.collection;
2  
3  import java.util.Collections;
4  import java.util.HashMap;
5  import java.util.Map;
6  
7  public class SyncMapDemo {
8      public static void main(String args []) {
9          Map<Integer, String> map = new HashMap<>(0);
10         map.put(1, "Id");
11         map.put(2, "Name");
12         map.put(3, "Salary");
13 
14         Map<Integer, String> output = Collections.synchronizedMap(map);
15 
16         System.out.println(output);
17     }
18 }

In the above code, at line 9, I create a map with key type as “Integer” and value type being “String”. Then I populate the map.

At line 14, I call static method “synchronizedMap” available on “Collections” class and pass the map as an argument.

The method returns a synchronized map.

In this way, we can create a synchronized map.

Please note after obtaining the synchronized map, any modification to source map will also affect the synchronized map and vice versa.

Leave a comment