Learnitweb

CopyOnWriteArrayList in Java

1. Introduction

CopyOnWriteArrayList is a class defined in java.util.concurrent package and is a member of Java Collections Framework. This class was introduced in Java 1.5. CopyOnWriteArrayList implements following interfaces:

  • Serializable
  • Cloneable
  • Iterable
  • Collection
  • List
  • RandomAccess

CopyOnWriteArrayList is a thread-safe variant of ArrayList. All mutative operations (add, set and so on) are implemented by creating a new copy of the underlying array.

Following are some important points to explain more:

  • For each mutative operation (like add or set), a fresh copy of the underlying array is created. Due to this reason, mutative operations on CopyOnWriteArrayList are not efficient.
  • Due to the above mentioned reason, CopyOnWriteArrayList should not be used when you have to perform large number of mutative operations.
  • CopyOnWriteArrayList should be used for concurrent modification when number of traversal operations are more frequent than in comparison to mutative operations and you don’t want to synchronize the traversal operations. CopyOnWriteArrayList removes the need to manually synchronize the threads modifying and traversing the array.
  • The iterator created over CopyOnWriteArrayList uses the CopyOnWriteArrayList‘s snapshot at that moment. This state of array does not change for the iterator for the life of iterator. So the iterator will not reflect the add, update or remove operations performed on the array. Due to the same reason, iterator never throws ConcurrentModificationException on CopyOnWriteArrayList.
  • Mutative methods of iterator like add, set or remove are not supported and throw UnsupportedOperationException.
  • CopyOnWriteArrayList like ArrayList allows all types of objects. Null elements are also allowed.

2. Constructors

  • CopyOnWriteArrayList()
  • CopyOnWriteArrayList(Collection c)
  • CopyOnWriteArrayList(E[] toCopyIn)

3. Example

In this tutorial, we’ll create a CopyOnWriteArrayList and an iterator to traverse it. After creating an iterator, we’ll add elements to it and will verify that the iterator use the snapshot of the array.

public class CopyOnWriteArrayListExample extends Thread {
	static CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>(new Integer[] { 1, 2, 3, 4 });

	public static void main(String[] args) {
		// create iterator. This will use snapshot of list 1, 2, 3, 4
		Iterator i = list.iterator();
		
		//add 2 elements
		list.add(5);
		list.add(6);
		
		//will print only 1, 2, 3, 4
		while (i.hasNext()) {
			System.out.println(i.next());
		}
	}
}

Output

1
2
3
4