Collections
Get Synchronized Set example
In this example we shall show you how to get a Synchronized Set. We are using a HashSet, but the same API applies to any type of Set implementation. The Collections API provides us with methods so as to get synchronized (thread-safe) Collections from specific Collections. To get a synchronized Set one should perform the following steps:
- Create a new HashSet.
- Populate the new set with elements, using the
add(E e)API method of the Set. - Invoke the
synchronizedSet(SetAPI method of Collections in order to return a synchronized (thread-safe) set backed by the specified set,s)
as described in the code snippet below.
package com.javacodegeeks.snippets.core;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class SynchronizedSetExample {
public static void main(String[] args) {
/*
Please note that the same API applies to any type of
Set implementation class e.g. TreeSet etc
*/
// Create a HashSet and populate it with elements
HashSet hashSet = new HashSet();
hashSet.add("element_1");
hashSet.add("element_2");
hashSet.add("element_3");
// static void synchronizedSet(Set set) method returns a synchronized Set from HashSet
Set syncSet = Collections.synchronizedSet(hashSet);
System.out.println("syncSet contains : " + syncSet);
}
}
Output:
syncSet contains : [element_1, element_2, element_3]
This was an example of how to get a Synchronized Set in Java.

