Java – How to get synchronized version of Set ?

In this article, we will discuss how to get synchronized version of Set using Collections class’s utility synchronizedSet() method

Q) How to make Synchronized Set ?

  • From original collection framework introduced in Java 1.2 version, by default HashSet, LinkedHashSet and TreeSet classes aren’t thread-safe i.e.; non-synchronized
  • But we can make it thread-safe using Collections utility synchronizedSet(set) method
  • While iterating synchronized Set, make sure to iterate inside synchronized block;
  • otherwise we may face non-deterministic behavior

From Java doc,

* It is imperative that the user manually synchronize on the returned
* set when iterating over it:

       Set s = Collections.synchronizedSet(new HashSet());
           ...
       synchronized (s) {
           Iterator i = s.iterator(); // Must be in the synchronized block
           while (i.hasNext())
               foo(i.next());
       }

* Failure to follow this advice may result in non-deterministic behavior.

1. To get Synchronized version of Set

Method signature:

public static Set synchronizedSet(Set<Object> set);

SynchronizedVersionOfSet.java

package in.bench.resources.java.collection;

import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SynchronizedVersionOfSet {

	public static void main(String[] args) {

		// creating HashSet object of type String
		HashSet<String> unSynchronizedSet = new HashSet<String>();

		// adding elements to HashSet object
		unSynchronizedSet.add("Facebook");
		unSynchronizedSet.add("LinkedIn");
		unSynchronizedSet.add("YouTube");
		unSynchronizedSet.add("Google");
		unSynchronizedSet.add("YouTube"); // duplicate

		// to get synchronized HashSet
		Set<String> synchronizedSet = Collections
				.synchronizedSet(unSynchronizedSet);

		System.out.println("Iterating through synchronized HashSet\n");

		// synchronized block
		synchronized(synchronizedSet) {

			Iterator<String> iterator = synchronizedSet.iterator();
			while (iterator.hasNext())
				System.out.println(iterator.next());
		}
	}
}

Output:

Iterating through synchronized HashSet

Google
LinkedIn
YouTube
Facebook

Note: similarly, we can make thread-safe for LinkedHashSet or TreeSet classes

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to get synchronized version of Map ?
Java - How to get synchronized version of List ?