Collections public static Set synchronizedSet(Set s) Method Example Program


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

Program

package com.candidjava;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use
 *              Collections.synchronizedSet(Set  s) method.
 */
public class CollectionssynchronizedSet {
	public static void main(String[] args) {
		Set set = new HashSet();
		set.add("karthik");
		set.add("mohan");
		set.add("kamal");
		set.add("hari");
		set.add("vinodh");
		Set synset = Collections.synchronizedSet(set);
		System.out.println("Synchronized set is :" + synset);
	}
}

Output

Synchronized set is :[hari, kamal, mohan, karthik, vinodh]

Explanation

public static Set synchronizedSet(Set s)
Returns a synchronized (thread-safe) set backed by the specified set. In order to guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set.
It is imperative that the user manually synchronize on the returned set when iterating over it:

  Set s = Collections.synchronizedSet(new HashSet());
      ...
  synchronized (s) {
      Iterator i = s.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 set will be serializable if the specified set is serializable.

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


Related Post

Comments


©candidjava.com