java.util.Collections.synchronizedMap() Method


Advertisements


Description

The synchronizedMap() method is used to return a synchronized (thread-safe) map backed by the specified map.

Declaration

Following is the declaration for java.util.Collections.synchronizedMap() method.

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)

Parameters

  • m -- This is the map to be "wrapped" in a synchronized map.

Return Value

  • The method call returns a synchronized view of the specified map.

Exception

  • NA

Example

The following example shows the usage of java.util.Collections.synchronizedMap()

package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String[] args) {
   // create map
   Map<String,String> map = new HashMap<String,String>();
      
   // populate the map
   map.put("1","TP"); 
   map.put("2","IS");
   map.put("3","BEST");
      
   // create a synchronized map
   Map<String,String> synmap = Collections.synchronizedMap(map);
     
   System.out.println("Synchronized map is :"+synmap);
   }
}

Let us compile and run the above program, this will produce the following result.

Synchronized map is :{3=BEST, 2=IS, 1=TP}

java_util_collections.htm

Advertisements