CopyOnWriteArrayList in Java With Examples

CopyOnWriteArrayList in Java is a thread safe implementation of List interface. CopyOnWriteArrayList was added in Java 1.5 and part of Collections framework.

Java ArrayList and ConcurrentModificationException

ArrayList is one of the basic implementations of List interface and it’s part of Java Collections Framework. We can use iterator to traverse through ArrayList elements.

Let’s check a sample program of ArrayList.

When we run above program, we get java.util.ConcurrentModificationException as soon as the ArrayList is modified.

It happens because ArrayList iterator is fail-fast by design. What it means is that once the iterator is created, if the ArrayList is modified, it throws ConcurrentModificationException.

If you check the console log, you will notice that exception is thrown by Iterator next() method. If you will look into the ArrayList source code, following method is called everytime we invoke next() on iterator that throws exception.

Here modCount is the ArrayList variable that holds the modification count and every time we use add, remove or trimToSize method, it increments. expectedModCount is the iterator variable that is initialized when we create iterator with same value as modCount. This explains why we don’t get exception if we use set method to replace any existing element.

So basically iterator throws ConcurrentModificationException if list size is changed.

CopyOnWriteArrayList in Java

Sometimes we want to add or remove elements from the list if we find some specific element, in that case we should use concurrent collection class – CopyOnWriteArrayList. This is a thread-safe variant of java.util.ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

CopyOnWriteArrayList introduces extra overload to the processing but it’s very effective when number of modifications are minimal compared to number of traversal operations.

If we change the implementation to CopyOnWriteArrayList, then we don’t get any exception and below is the output produced.

Notice that it allows the modification of list, but it doesn’t change the iterator and we get same elements as it was on original list.

By admin

Leave a Reply

%d bloggers like this: