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(Set s) API method of Collections in order to return a synchronized (thread-safe) set backed by the specified set,

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();
    // static void synchronizedSet(Set set) method returns a synchronized Set from HashSet
    Set syncSet = Collections.synchronizedSet(hashSet);

    System.out.println("syncSet contains : " + syncSet);


syncSet contains : [element_1, element_2, element_3]

This was an example of how to get a Synchronized Set in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button