Home > Java > javaTutorial > Get synchronized map from Java TreeMap

Get synchronized map from Java TreeMap

WBOY
Release: 2023-09-02 16:41:02
forward
1253 people have browsed it

从 Java TreeMap 获取同步地图

To get a synchronized Map from a TreeMap in Java, we can use the built-in method "synchronizedMap()" of the Collection interface. Here, TreeMap is a class used to implement the NavigableMap interface. It stores the map's elements in a tree structure. It provides an efficient alternative to storing key-value pairs in sorted order. By default, TreeMap is not synchronized. In this article, we will explain the necessity of synchronization and its practical implementation through a sample program.

Synchronized map of tree map

Treemap is not thread-safe, which means when we implement it in a multi-threaded environment, multiple threads can access and modify it simultaneously without any coordination. This can lead to data inconsistencies and unexpected behavior of elements. It may also affect the outcome of the operation.

Therefore, we need to use synchronizedMap() to synchronize access to TreeMap elements. This method creates a wrapper around the original TreeMap and locks it when a thread attempts to access or modify it.

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

grammar

Collections.synchronizedMap(instanceOfTreeMap);
Copy after login

Here, "Collections" is a class of the collection interface.

The general syntax of TreeMap is as follows -

grammar

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

method

  • First, import the "java.util" package to enable the TreeMap class.

  • Then, create a TreeMap where the key is of type String and the value is Integer type.

  • Use the built-in method "put()" to store some elements in a collection

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

  • Finally, print the new synchronized map and exit.

Example 1

The following example illustrates how to use synchronizedMap() to synchronize the specified TreeMap.

< /h3>
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);
   }
}
Copy after login

Output

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

method

  • First, import the "java.util" package to enable the TreeMap class.

  • Then, create a TreeMap where the keys are String type and the values ​​are Integer type

  • Use the built-in method "put()" to store some elements in a collection

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

  • Finally, define a synchronization block. Within this block, the items are printed using the "keySet()" method using a for-each loop.

Example 2

In the following example, we will use the synchronizedMap() method and a synchronized block to synchronize the given TreeMap< /p>

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));
         }
      }
   }
}
Copy after login

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
Copy after login

in conclusion

Synchronization is the process of establishing coordination and ensuring correct communication between two or more activities. Since out-of-synchronization of TreeMap may lead to data inconsistency, we need to synchronize it. The built-in method "Collections.synchronizedMap()" is a more convenient way to perform this task.

The above is the detailed content of Get synchronized map from Java TreeMap. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template