Collections public static SortedMap synchronizedSortedMap(SortedMap m) Method Example Program


Returns a synchronized (thread-safe) sorted map backed by the specified sorted map. In order to guarantee serial access, it is critical that all access to the backing sorted map is accomplished through the returned sorted map (or its views).

Program

package com.candidjava;

import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use
 *              Collections.synchronizedSortedMap(SortedMap <K,V> m) method.
 */
public class CollectionssynchronizedSortedMap {
	public static void main(String[] args) {
		SortedMap<String, String> map = new TreeMap<String, String>();
		map.put("1", "karthik");
		map.put("5", "mohan");
		map.put("3", "kamal");
		map.put("6", "hari");
		map.put("2", "anandh");
		map.put("3", "vinodh");
		SortedMap<String, String> sortedmap = (SortedMap<String, String>) Collections
				.synchronizedSortedMap(map);
		System.out.println("Synchronized sorted map is :" + sortedmap);
	}
}

Output

Synchronized sorted map is :{1=karthik, 2=anandh, 3=vinodh, 5=mohan, 6=hari}

Explanation

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

  SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
      ...
  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());
  }
 
or:
  SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
  SortedMap m2 = m.subMap(foo, bar);
      ...
  Set s2 = m2.keySet();  // Needn't be in synchronized block
      ...
  synchronized (m) {  // Synchronizing on m, not m2 or s2!
      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 sorted map will be serializable if the specified sorted map is serializable.

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


Related Post

Comments


©candidjava.com