Skip to content
Related Articles

Related Articles

How to Synchronize HashMap in Java?
  • Difficulty Level : Medium
  • Last Updated : 28 Dec, 2020

HashMap is part of the Collection’s framework of java. It stores the data in the form of key-value pairs.  These values of the HashMap can be accessed by using their respective keys. The key-value pairs can be accessed using their indexes (of Integer type).

HashMap is similar to HashTable in java. The main difference between HashTable and HashMap is that HashTable is synchronized but HashMap is not synchronized. Also, a HashMap can have one null key and any number of null values. The insertion order is not preserved in the HashMap.

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.

HashMap can be synchronized using the Collections.synchronizedMap() method.

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.

Code:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// synchronization of HashMap
  
import java.util.*;
  
public class GFG {
    public static void main(String[] argv) throws Exception
    {
  
        try {
            // create a HashMap object
            Map<String, String> hMap
                = new HashMap<String, String>();
            
            // add elements into the Map
            hMap.put("1", "Welcome");
            hMap.put("2", "To");
            hMap.put("3", "Geeks");
            hMap.put("4", "For");
            hMap.put("5", "Geeks");
            
            System.out.println("Map : " + hMap);
            
            // Synchronizing the map
            Map<String, String> sMap
                = Collections.synchronizedMap(hMap);
  
            // printing the Collection
            System.out.println("Synchronized map is : "
                               + sMap);
        }
  
        catch (IllegalArgumentException e) 
        {
            System.out.println("Exception thrown : " + e);
        }
    }
}

chevron_right


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}

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :