Difference Between ArrayList And CopyOnWriteArrayList in Java

ArrayList is part of Java from version 1.2 where as CopyOnWriteArrayList was added in Java 5 as a thread-safe variant of ArrayList. In this post we’ll see the differences between ArrayList and CopyOnWriteArrayList in Java.

CopyOnWriteArrayList Vs ArrayList in Java

1- Thread Safety:

CopyOnWriteArrayList is thread safe. Thread safety in CopyOnWriteArrayList is achieved by making a fresh copy of the underlying array for all mutative operations (add, set, and so on).

ArrayList in Java is not thread safe.

2- Iterator fail-fast or fail-safe:

The iterator returned by CopyOnWriteArrayList is fail-safe and the iterator is guaranteed not to throw ConcurrentModificationException. This array never changes during the lifetime of the iterator, even if there is any mutative operation invoked on the CopyOnWriteArrayList while it is iterated that will result in creation of fresh copy of the underlying array, so interference is impossible.

The iterators returned by ArrayList’s iterator and listIterator methods are fail-fast. If the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException.

Here is an example showing the iteration using an iterator with both ArrayList and CopyOnWriteArrayList.


Here it can be seen that the ConcurrentModificationException is thrown as there is an attempt to add an element to the ArrayList while it is iterated.

With CopyOnWriteArrayList


As you can see now ConcurrentModificationException is not thrown but the iterator doesn’t display the newly added element as it is iterating on a different copy.

3- Performance:

Since the underlying array is copied every time there is a mutative operation, using CopyOnWriteArrayList is ordinarily too costly, but may be more efficient in scenarios where traversal operations vastly outnumber mutations.

ArrayList is not synchronized and underlying array is not copied unless until size of the array has to be changed dynamically so ArrayList is faster.

That’s all for the topic Difference Between ArrayList And CopyOnWriteArrayList in Java. If something is missing or you have something to share about the topic please write a comment.

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.