CopyOnWriteArrayList in Java – Complete Guide

CopyOnWriteArrayList in Java was introduced in Java 1.5 and it is part of Collections framework.

CopyOnWriteArrayList in Java is a thread safe class and it is the implementation of List interface.

CopyOnWriteArrayList in Java is a thread-safe type of ArrayList in which each operation is implemented by making a new copy of array.

Hierarchy of CopyOnWriteArrayList in Java

CopyOnWriteArrayList Hierarchy

CopyOnWriteArrayList class Declaration

java.util.concurrent
Class CopyOnWriteArrayList<E>
java.lang.Object
java.util.concurrent.CopyOnWriteArrayList<E>
Type Parameters:
E - the type of elements held in this collection
All Implemented Interfaces:
Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
public class CopyOnWriteArrayList<E>
extends Object
implements List<E>, RandomAccess, Cloneable, Serializable

Some Important Points

  • CopyOnWriteArrayList creates a fresh copy of underlying ArrayList for every create or update operation and both will be synchronized in nature. So there will not be any effect on threads which are performing read operation.
  • Its performance is costly because for every update operation it creates a cloned copy. Hence CopyOnWriteArrayList is the best for use if frequent operation is only read operation.
  • It is a thread safe version for ArrayList.
  • Insertion order is preserved and duplicates are allowed in CopyOnWriteArrayList.
  • The iterator of CopyOnWriteArrayList is fail-safe.
  • Remove operation can not be performed in it while iterating, otherwise Run-time exception occurs saying UnsupportedOperationException.
  • It does not throw ConcurrentModificationException.
  • It creates a fresh copy of array whenever iterator is created therefore performance is slower than ArrayList.

When to use CopyOnWriteArrayList

We can use CopyOnWriteArrayList over ArrayList in following cases:

  • When list has to be used in concurrent environment.
  • When there are frequent read operations and lesser write operations.
  • When we do not want to synchronize the thread access.

CopyOnWriteArrayList Example

Below is the simple example using iterator.

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;



public class CopyOnWriteArrayListExample 
{
	public static void main(String args[]) 
	{
	     
        CopyOnWriteArrayList<String> threadSafe = new CopyOnWriteArrayList<String>();
        threadSafe.add("USA");
        threadSafe.add("UK");
        threadSafe.add("AUS");
     
        //add, remove operator is not supported by CopyOnWriteArrayList iterator
        Iterator<String> failSafeItr = threadSafe.iterator();
        while(failSafeItr.hasNext()){
            System.out.printf("Read from CopyOnWriteArrayList : %s %n", failSafeItr.next());
          //  failSafeItr.remove(); //not supported in CopyOnWriteArrayList in Java
        }
    }

}
#Output#
Read from CopyOnWriteArrayList : USA 
Read from CopyOnWriteArrayList : UK 
Read from CopyOnWriteArrayList : AUS
If you uncomment the  failSafeItr.remove() in above program then below Output will come.

Read from CopyOnWriteArrayList : USA 
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.concurrent.CopyOnWriteArrayList$COWIterator.remove(CopyOnWriteArrayList.java:1178)
	at CopyOnWriteArrayListExample.main(CopyOnWriteArrayListExample.java:20)


Thread safety in CopyOnWriteArrayList

CopyOnWriteArrayList in Java is thread safe variant of List interface in java. This thread safety is being achieved by always making a fresh copy of the array with every mutative operations (set, add ,etc). It is self explanatory from the name “Copy on write” whenever value is changed then create a copy.

CopyOnWriteArrayList has a fail-safe iterator

Iterator returned by the CopyOnWriteArrayList in Java is fail-safe in nature. As you already know by now that any mutation will result in a fresh copy of array. Therefore the array that the iterator has a reference to will never change during the lifetime of iterator, thus interference is never possible and the iterator is guaranteed to be not to throw ConcurrentModificationException.

Conclusion

You have learnt about hierarchy of CopyOnWriteArrayList in Java, when to use it, CopyOnWriteArrayList Example, Thread safety in CopyOnWriteArrayList, CopyOnWriteArrayList has a fail-safe iterator.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply