Collections public static Map synchronizedMap(Map m) Method Example Program


Returns a synchronized (thread-safe) map backed by the specified map.

Program

package com.candidjava;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author karthikeyan.T
 * @description :The following code shows how to use
 *              Collections.synchronizedMap(Map <K,V> m) method.
 */
public class CollectionsSynchronizedMap {
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("1", "karthik");
		map.put("4", "kamal");
		map.put("3", "mohan");
		Map<String, String> synmap = Collections.synchronizedMap(map);
		System.out.println("Synchronized map is :" + synmap);
	}
}

Output

Synchronized map is :{1=karthik, 3=mohan, 4=kamal}

Explanation

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
Returns a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map.
It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:

  Map m = Collections.synchronizedMap(new HashMap());
      ...
  Set s = m.keySet();  // Needn't be in synchronized block
      ...
  synchronized (m) {  // Synchronizing on m, not s!
      Iterator i = s.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }
 
Failure to follow this advice may result in non-deterministic behavior.
The returned map will be serializable if the specified map is serializable.

Parameters:
m - the map to be "wrapped" in a synchronized map.
Returns:
a synchronized view of the specified map.


Related Post

Comments


©candidjava.com