Java Utility Library

Java Collections - synchronizedCollection() Method



The java.util.Collections.synchronizedCollection() method returns a synchronized (thread-safe) collection backed by the specified collection.

Syntax

public static <T> Collection<T> synchronizedCollection(Collection<T> c)

Here, T is the type of element in the collection.


Parameters

c Specify the collection to be "wrapped" in a synchronized collection.

Return Value

Returns a synchronized view of the specified collection.

Exception

NA.

Example:

In the example below, the java.util.Collections.synchronizedCollection() method returns a synchronized view of the given collection.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a collection list object
    Collection<Integer> MyList = new ArrayList<Integer>();

    //populating the list
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);

    //printing the list
    System.out.println("MyList contains: " + MyList); 

    //creating an synchronized view of the collection
    Collection NewList = Collections.synchronizedCollection(MyList);

    //printing the synchronized collection
    System.out.println("NewList contains: " + NewList);   
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30, 40]
NewList contains: [10, 20, 30, 40]

❮ Java.util - Collections