Java Utility Library

Java Collections - synchronizedSet() Method



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

Syntax

public static <T> Set<T> synchronizedSet(Set<T> s)

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


Parameters

s Specify the set to be "wrapped" in a synchronized set.

Return Value

Returns a synchronized view of the specified set.

Exception

NA.

Example:

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

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a Set object
    Set<Integer> MySet = new HashSet<Integer>();

    //populating the set
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

    //printing the set
    System.out.println("MySet contains: " + MySet); 

    //creating an synchronized view of the set
    Set NewSet = Collections.synchronizedSet(MySet);

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

The output of the above code will be:

MySet contains: [20, 40, 10, 30]
NewSet contains: [20, 40, 10, 30]

❮ Java.util - Collections