Collections public static List synchronizedList(List list) Method Example Program


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

Program

package com.candidjava;

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

/**
 * 
 * @author karthikeyan.T
 * @description The following code shows how to use
 *              Collections.synchronizedList(List  list) method.
 */
public class CollectionssynchronizedList {
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add("karthik");
		list.add("mohan");
		list.add("kamal");
		list.add("hari");
		list.add("vinodh");
		List synlist = Collections.synchronizedList(list);
		System.out.println("Sunchronized list is :" + synlist);
	}
}

Output

Sunchronized list is :[karthik, mohan, kamal, hari, vinodh]

Explanation

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

  List list = Collections.synchronizedList(new ArrayList());
      ...
  synchronized (list) {
      Iterator i = list.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 list will be serializable if the specified list is serializable.

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


Related Post

Comments


©candidjava.com