The synchronizedCollection() method of java.util.Collections class is used to return 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.
Syntax:
public static <T> Collection<T>
synchronizedCollection(Collection<T> c)
Parameters: This method takes the collection c as a parameter to be “wrapped” in a synchronized collection.
Return Value: This method returns a synchronized view of the specified collection.
Below are the examples to illustrate the synchronizedCollection() method
Example 1:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
List<String> vector = new ArrayList<String>();
vector.add( "A" );
vector.add( "B" );
vector.add( "C" );
vector.add( "D" );
vector.add( "E" );
System.out.println( "Collection : " + vector);
Collection<String> c = Collections
.synchronizedCollection(vector);
System.out.println( "Synchronized view"
+ " of collection : " + c);
}
catch (IndexOutOfBoundsException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output
Collection : [A, B, C, D, E]
Synchronized view of collection : [A, B, C, D, E]
Example 2:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
List<Integer> vector = new ArrayList<Integer>();
vector.add( 20 );
vector.add( 30 );
vector.add( 40 );
vector.add( 50 );
vector.add( 60 );
System.out.println( "Collection : " + vector);
Collection<Integer> c = Collections
.synchronizedCollection(vector);
System.out.println( "Synchronized view is : " + c);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Collection : [20, 30, 40, 50, 60]
Synchronized view is : [20, 30, 40, 50, 60]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 Jul, 2021
Like Article
Save Article