Synchronize access to an ArrayList in Java
We explained the principle of synchronization earlier when we talked about the difference between Vector and ArrayList. ArrayList is not synchronized and should never be used in a multi-threaded environment without a synchronization.There are two ways to synchronize:
- Use the method Collections.synchronizedList()
- Use a protected version of ArrayList: CopyOnWriteArrayList
1) synchronize ArrayList with the Collections.synchronizedList()
An important point to note here is that iterator must be inside the synchronized block as shown in the example below:
import java.util.ArrayList;Runtime:
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class ArrayListSynchronized{
public static void main(String[] args) {
// Create an ArrayList< String> synchronized
List< String> slist = Collections.synchronizedList(new ArrayList< String> ());
//add items to ArrayList
slist.add("1");
slist.add("5");
slist.add("2");
slist.add("7");
System.out.println("browse synchronized list:");
synchronized(slist) {
Iterator< String> iterator = slist.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
}
}
}
browse synchronized list:
1
5
2
7
2) Using CopyOnWriteArrayList
import java.util.Iterator;Run:
public class CopyOnWriteArrayList{
public static void main(String[] args) {
java.util.concurrent.CopyOnWriteArrayList< String> al =
new java.util.concurrent.CopyOnWriteArrayList< String> ();
//add items to ArrayList
al.add("notebook");
al.add("kit");
al.add("USB stick");
al.add("calculator");
System.out.println("browse synchronized list:");
Iterator< String> iterator = al.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
}
}
browse synchronized list:
notebook
kit
USB stick
calculator