How to get synchronized version Collection

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

 

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.

 

Example: 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

 

References:

 

Happy Coding !!
Happy Learning !!

How to swap elements of ArrayList
How to get synchronized version of Map