How do I synchronize a List or other Collection in Java?
Author: Deron Eriksson
Description: This Java tutorial describes how to synchronize lists and other collections in Java.
Tutorial created using: Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)


In JavaSW, normally collections aren't synchronized, which leads to fast performance. However, in multi-threaded situations, it can be very useful for collections to be synchronized. The Java Collections class has several static methods on it that provide synchronized collections. These methods are:

Synchronized Collection Methods of Collections class
Collections.synchronizedCollection(Collection<T> c)
Collections.synchronizedList(List<T> list)
Collections.synchronizedMap(Map<K,V> m)
Collections.synchronizedSet(Set<T> s)
Collections.synchronizedSortedMap(SortedMap<K,V> m)
Collections.synchronizedSortedSet(SortedSet<T> s)

As an example, let's take a normal list (implemented by the ArrayList class) and make it synchronized. This is shown in the SynchronizedListExample class. We pass the Collections.synchronizedList method a new ArrayList of Strings. The method returns a synchronized List of Strings.

SynchronizedListExample.java

package com.cakes;

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

public class SynchronizedListExample {

	public static void main(String[] args) {

		List<String> syncList = Collections.synchronizedList(new ArrayList<String>());

		syncList.add("one");
		syncList.add("two");
		syncList.add("three");

		// when iterating over a synchronized list, we need to synchronize access to the synchronized list
		synchronized (syncList) {
			Iterator<String> iterator = syncList.iterator();
			while (iterator.hasNext()) {
				System.out.println("item: " + iterator.next());
			}
		}

	}

}

Notice that when iterating over the list, this access is still done using a synchronized block that locks on the syncList object. In general, iterating over a synchronized collection should be done in a synchronized block. See the javadocs for the Collections class for more information.

Also, it can be good practice to synchronize your code in other ways when accessing a synchronized collection to ensure that you obtain the behavior you expect.