The
synchronizedList() method of
java.util.Collections class is used to return 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.
Syntax:
public static <T> List<T>
synchronizedList(List<T> list)
Parameters: This method takes the
list as a parameter to be “wrapped” in a synchronized list.
Return Value: This method returns a
synchronized view of the specified list.
Below are the examples to illustrate the
synchronizedList() method
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
System.out.println("List : " + list);
List<String> synlist = Collections
.synchronizedList(list);
System.out.println("Synchronized list is : " + synlist);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Output:
List : [A, B, C, D, E]
Synchronized list is : [A, B, C, D, E]
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
List<Integer> list = new ArrayList<Integer>();
list.add(20);
list.add(30);
list.add(40);
list.add(50);
list.add(60);
System.out.println("List : " + list);
List<Integer> synlist = Collections
.synchronizedList(list);
System.out.println("Synchronized list is : " + synlist);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Output:
List : [20, 30, 40, 50, 60]
Synchronized list is : [20, 30, 40, 50, 60]
Last Updated :
08 Oct, 2018
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...