Collections

Get Synchronized Map example

With this example we are going to demonstrate how to get a synchronized Map. We are using a HashMAp as example, but the same API applies to any type of Map implementation class e.g. TreeMap etc. The Collections API provides methods that return synchronized (thread-safe) collections (Lists, Sets, Maps). In short, to get a synchronized Map you should:

  • Create a new HashMap.
  • Populate the map with elements, using the put(K key, V value) API method of the HashMap.
  • Invoke the synchronizedMap(Map map) API method of Collections. It returns a synchronized Map from the provided HashMap.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
 
public class SynchronizedMapExample {
 
  public static void main(String[] args) {

    /*

Please note that the same API applies to any type of 

Map implementation class e.g. TreeMap etc
     */

    // Create HashMap and populate it with elements
    HashMap hashMap = new HashMap();
    hashMap.put("key_1","value_1");
    hashMap.put("key_2","value_2");
    hashMap.put("key_3","value_3");
 
    // static void synchronizedMap(Map map) method returns a synchronized Map from the provided HashMap
    Map syncMap = Collections.synchronizedMap(hashMap);

    System.out.println("syncMap contains : " + syncMap);
 
  }
}

Output:

syncMap contains : {key_3=value_3, key_2=value_2, key_1=value_1}

 
This was an example of how to get a synchronized Map in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button