Getting Synchronized Map from Java TreeMap


To get the synchronized Map from a TreeMap in Java, we can use an in-built method of Collection interface called ‘synchronizedMap()’. Here, TreeMap is a class that is used to implement NavigableMap Interface. It stores the elements of the map in a tree structure. It provides an efficient alternative to store the key-value pairs in sorted order. By default, a TreeMap is not synchronized. In this article, we will explain the need for synchronization and its practical implementation through example programs.

Synchronized Map from a Tree Map

A Tree Map is not thread-safe 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 TreeMap using ‘synchronizedMap()’. This method creates a wrapper around the original TreeMap and locks it whenever a thread tries to access or modify it.

The synchronizedMap() is a static method of the Collections class that takes the instance of TreeMap collection as a parameter and returns a synchronized Map from it.

Syntax

Collections.synchronizedMap(instanceOfTreeMap);

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

The general syntax for TreeMap is as follows −

Syntax

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

Approach

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

  • Then, create a TreeMap 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 TreeMap.

import java.util.*;
public class Maps {
   public static void main(String[] args) {
      TreeMap<String, Integer> cart = new TreeMap<>();
      // 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);
      // print synchronized map from TreeMap
      Map mapSynched = Collections.synchronizedMap(cart);
      System.out.println("Synchronized Map from TreeMap: " + mapSynched);
   }
}

Output

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

Approach

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

  • Then, create a TreeMap 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 TreeMap

import java.util.*;
public class Maps {
   public static void main(String[] args) {
      TreeMap<String, Integer> cart = new TreeMap<>();
      // 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 new synchronized Map
      Map<String, Integer> mapSynched = Collections.synchronizedMap(cart);
      System.out.println("Synchronized Map from TreeMap: " );
      // printing synchronized map from TreeMap
      synchronized (mapSynched) {
         for (String unKey : mapSynched.keySet()) {
            System.out.println("Item: " + unKey + ", Quantity: " +
            cart.get(unKey));
         }
      }
   }
}

Output

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

Conclusion

Synchronization is the process of establishing coordination and ensuring proper communication between two or more activities. Since a TreeMap 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

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements