Getting Synchronized Map from Java HashMap


To get the synchronized Map from a Hash Map in Java, we can use an in-built method of Collection interface named ‘synchronized Map()’. Here, the Hash Map is a class that is used to implement Map Interface. It stores its element in key-value pairs. The Key is an object that is used to fetch and receive value associated with it. It has access to all the methods of Map Interface, it does not have any additional methods of its own. Duplicate values are not allowed, although we can store null values and keys. In this article, we will explore the need for synchronization and its practical implementation through example programs.

Synchronized Map from a Hash Map

A synchronized map is a map that can be safely accessed by multiple threads without causing concurrency issues. On the other hand, a Hash Map is not synchronized which means when we implement it in a multi-threading environment, multiple threads can access and modify it at the same time without any coordination. This can lead to data inconsistency and unexpected behavior of elements. It may also affect the results of an operation.

Therefore, we need to synchronize the access to the elements of Hash Map using ‘synchronizedMap()’. This method creates a wrapper around the original HashMap and locks it whenever a thread tries to access or modify it.

The synchronizedMap() is a static method of the Collections class that takes an instance of HashMap collection as a parameter and returns a synchronized Map from it. However,it is important to note that only the map itself is synchronized, not its views such as keyset and entrySet. Therefore, if we want to iterate over the synchronized map, we need to use a synchronized block or a lock to ensure exclusive access.

Syntax

Collections.synchronizedMap(instanceOfHashMap);

Here, ‘Collections’ is a class of the Collection Interface.

The general syntax for Synchronized block is as follows −

Syntax

synchronized(instanceOfSynchronizedMap) {
   // operation
}

To use the HashMap collection, we need to create its instance using the following syntax

Syntax

HashMap<TypeOfKey, TypeOfValue> nameOfMap = new HashMap<>();

Approach

  • First, import the ‘java.util’ package to enable the use of HashMap class.

  • First, import the ‘java.util’ package to enable the use of HashMap class.  Then, create a HashMap where the key will be of type String and values will be of Integer type.

  • Use the built-in method ‘put()’ to store some elements in the collection.

  • Now, synchronize these elements and store them in a variable of type Map.

  • In the end, print the new synchronized map and exit.

Example 1

The following example illustrates how we can use the synchronizedMap() to synchronize a specified HashMap.

import java.util.*;
public class Maps {
   public static void main(String[] args) {
      HashMap<String, Integer> cart = new HashMap<>();
      // Adding elements in the cart map
      cart.put("Butter", 5);
      cart.put("Milk", 10);
      cart.put("Rice", 20);
      cart.put("Bread", 2);
      cart.put("Peanut", 2);
      // printing synchronized map from HashMap
      Map mapSynched = Collections.synchronizedMap(cart);
      System.out.println("Synchronized Map from HashMap: " + mapSynched);
   }
}

Output

Synchronized Map from HashMap: {Peanut=2, Butter=5, Milk=10, Rice=20, Bread=2}

Approach

  • Create a HashMap where the key will be of type String and values will be of Integer type.

  • Use the built-in method ‘put()’ to store some elements in the collection.

  • Now, synchronize these elements using synchronizedMap() method and store them in a new collection of the Map.

  • In the end, define a synchronized block. Inside this block take a for-each loop to print the items using ‘keySet()’ method.

Example 2

In the following example, we will use the synchronizedMap() method and a synchronized block to synchronize the given HashMap

import java.util.*;
public class Maps {
   public static void main(String[] args) {
      HashMap<String, Integer> cart = new HashMap<>();
      // Adding elements in the cart map
      cart.put("Butter", 5);
      cart.put("Milk", 10);
      cart.put("Rice", 20);
      cart.put("Bread", 2);
      cart.put("Peanut", 2);
      // creating a new synchronized Map from HashMap
      Map<String, Integer> mapSynched = Collections.synchronizedMap(cart);
      System.out.println("New Synchronized Map from HashMap: ");
      // printing synchronized map from HashMap
      synchronized (mapSynched) {
         for (String unKey : mapSynched.keySet()) {
            System.out.println("Item: " + unKey + ", Quantity: " +
            cart.get(unKey));
         }
      }
    }
}

Output

New Synchronized Map from HashMap:
Item: Peanut, Quantity: 2
Item: Butter, Quantity: 5
Item: Milk, Quantity: 10
Item: Rice, Quantity: 20
Item: Bread, Quantity: 2

Conclusion

Synchronization is the process of establishing coordination and ensuring proper communication between two or more activities. Since a HashMap is not synchronized which may cause data inconsistency, therefore, we need to synchronize it. The in-built method ‘Collections.synchronizedMap()’ is a more convenient way of performing this task.

Updated on: 21-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements