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:
SerializableCloneableIterableCollectionListRandomAccess
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
addorset), a fresh copy of the underlying array is created. Due to this reason, mutative operations onCopyOnWriteArrayListare not efficient. - Due to the above mentioned reason,
CopyOnWriteArrayListshould not be used when you have to perform large number of mutative operations. CopyOnWriteArrayListshould 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.CopyOnWriteArrayListremoves the need to manually synchronize the threads modifying and traversing the array.- The iterator created over
CopyOnWriteArrayListuses theCopyOnWriteArrayList‘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 throwsConcurrentModificationExceptiononCopyOnWriteArrayList. - Mutative methods of iterator like
add,setorremoveare not supported and throwUnsupportedOperationException. CopyOnWriteArrayListlikeArrayListallows all types of objects.Nullelements 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
