How to get synchronized version of List

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

How to make Synchronized List ?

  • From original collection framework introduced in Java 1.2 version, by default ArrayList/LinkedList classes aren’t thread-safe i.e.; non-synchronized
  • But we can make it thread using Collections utility synchronizedList(list) method
  • While iterating synchronized List, 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
* list when iterating over it:

   List list = Collections.synchronizedList(new ArrayList());
           ...
       synchronized (list) {
           Iterator i = list.iterator(); // Must be in 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 ArrayList

Method signature:

public static List synchronizedList(List<Object> list);

SynchronizedVersionOfList.java

package in.bench.resources.java.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class SynchronizedVersionOfList {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> unSynchronizedList = new ArrayList<String>();

		// adding elements to ArrayList object
		unSynchronizedList.add("Facebook");  
		unSynchronizedList.add("LinkedIn"); 
		unSynchronizedList.add("YouTube");
		unSynchronizedList.add("Google");

		// to get synchronized ArrayList
		List<String> synchronizedList = Collections
				.synchronizedList(unSynchronizedList);

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

		// synchronized block
		synchronized(synchronizedList) {

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

Output:

Iterating through synchronized ArrayList

Facebook
LinkedIn
YouTube
Google

Note: similarly, we can make thread-safe for LinkedList/Vector class

 

References:

 

Happy Coding !!
Happy Learning !!

How to get synchronized version of Set
How to count duplicate elements of ArrayList