Collections public static Collection synchronizedCollection(Collection c) Method Example Program


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

Program

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use
 *              Collections.synchronizedCollection(Collection <T> c) method.
 */
public class CollectionssynchronizedCollection {
	public static void main(String[] args) {
		List<String> vector = new ArrayList<String>();
		vector.add("karthik");
		vector.add("mohan");
		vector.add("kamal");
		vector.add("hari");
		vector.add("vinodh");
		Collection<String> c = Collections.synchronizedCollection(vector);
		System.out.println("Synchronized view is :" + c);
	}
}

Output

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

Explanation

public static <T> Collection<T> synchronizedCollection(Collection<T> c)
Returns a synchronized (thread-safe) collection backed by the specified collection. In order to guarantee serial access, it is critical that all access to the backing collection is accomplished through the returned collection.
It is imperative that the user manually synchronize on the returned collection when iterating over it:

  Collection c = Collections.synchronizedCollection(myCollection);
     ...
  synchronized (c) {
      Iterator i = c.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 collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object's equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.

The returned collection will be serializable if the specified collection is serializable.

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


Related Post

Comments


©candidjava.com