Collections public static SortedSet synchronizedSortedSet(SortedSet s) Method Example program


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

Program

package com.candidjava;

import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use
 *              Collections.synchronizedSortedSet(SortedSet <T> s) method.
 */
public class CollectionsSynchronizedSortedSet {
	public static void main(String[] args) {
		SortedSet<String> set = new TreeSet<String>();
		set.add("karthik");
		set.add("mohan");
		set.add("kamal");
		set.add("hari");
		SortedSet<String> sorset = Collections.synchronizedSortedSet(set);
		System.out.println("Sorted set is :" + sorset);
	}
}

Output

Sorted set is :[hari, kamal, karthik, mohan]

Explanation

public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
Returns a synchronized (thread-safe) sorted set backed by the specified sorted set. In order to guarantee serial access, it is critical that all access to the backing sorted set is accomplished through the returned sorted set (or its views).
It is imperative that the user manually synchronize on the returned sorted set when iterating over it or any of its subSet, headSet, or tailSet views.

  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
      ...
  synchronized (s) {
      Iterator i = s.iterator(); // Must be in the synchronized block
      while (i.hasNext())
          foo(i.next());
  }
 
or:
  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
  SortedSet s2 = s.headSet(foo);
      ...
  synchronized (s) {  // Note: s, not s2!!!
      Iterator i = s2.iterator(); // Must be in the synchronized block
      while (i.hasNext())
          foo(i.next());
  }
 
Failure to follow this advice may result in non-deterministic behavior.
The returned sorted set will be serializable if the specified sorted set is serializable.

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


Related Post

Comments


©candidjava.com