In this article, we will discuss how to get synchronized version of Collection using Collections class’s utility synchronizedCollection() method
Q) How to make Synchronized Collection ?
- From original collection framework introduced in Java 1.2 version, by default all collections classes aren’t thread-safe i.e.; non-synchronized
- But we can make it thread-safe using Collections utility synchronizedCollection(col) method
- While iterating synchronized Collection, 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
* collection when iterating over it:
Collection c = Collections.synchronizedCollection(myCollection); ... synchronized (c) { Iterator i = c.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 Collection
Method signature:
public static Collection synchronizedCollection(Collection<Object> col);
SynchronizedVersionOfCollection.java
package in.bench.resources.java.collection;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.TreeSet;
public class SynchronizedVersionOfCollection {
public static void main(String[] args) {
// creating TreeSet object of type String
TreeSet<String> unSynchronizedCollection = new TreeSet<String>();
// adding elements to TreeSet object
unSynchronizedCollection.add("Facebook");
unSynchronizedCollection.add("LinkedIn");
unSynchronizedCollection.add("YouTube");
unSynchronizedCollection.add("Google");
unSynchronizedCollection.add("YouTube"); // duplicate
// to get synchronized Collection
Collection<String> synchronizedCollection = Collections
.synchronizedCollection(unSynchronizedCollection);
System.out.println("Iterating synchronized Collection\n");
// iterate inside synchronized block
synchronized(synchronizedCollection) {
Iterator<String> itr = synchronizedCollection.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}
}
Output:
Iterating synchronized Collection
Facebook
Google
LinkedIn
YouTube
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/TreeSet.html
Happy Coding !!
Happy Learning !!