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:
- Java – How to get synchronized version of List ?
- Java – How to get synchronized version of Set ?
- Java – How to get synchronized version of Map ?
- Java – How to get synchronized version Collection ?
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/class-use/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
Happy Coding !!
Happy Learning !!