This post will discuss the differences and similarities between ArrayList and CopyOnWriteArrayList in Java.

The CopyOnWriteArrayList class is a thread-safe variant of the ArrayList class, therefore shares several similarities with its parent class:

  1. Both are members of the Java Collections Framework and implements the List interface.
  2. Both internally uses an array data structure to store the list, which can grow and shrink dynamically to accommodate new elements if needed.
  3. Both are ordered, i.e., they maintain element insertion order.
  4. Both allows duplicates and null values.

 
Now let’s discuss some of the major differences between the ArrayList and CopyOnWriteArrayList implementations.

1. Synchronization

The primary difference between an ArrayList and CopyOnWriteArrayList is that a CopyOnWriteArrayList is synchronized, whereas an ArrayList is not synchronized.

This means that only a single thread can operate on a CopyOnWriteArrayList instance at a time and other threads need to wait until that lock is released, whereas multiple threads can operate on an ArrayList instance concurrently.

Note that an ArrayList can be made thread-safe with the help of Collections.synchronizedList() method.

2. Performance

ArrayList is much faster than CopyOnWriteArrayList even though both use array as an underlying data structure. This is because, unlike an ArrayList, CopyOnWriteArrayList is synchronized, and multiple threads cannot operate upon it simultaneously.

3. Fail-fast

The iterators returned by iterator() and listIterator() methods of an ArrayList are fail-fast and throws ConcurrentModificationException if ArrayList is structurally modified after the iterator is created except through the iterator’s own remove() or add() methods.

On the other hand, the iterators returned by CopyOnWriteArrayList are fail-safe and guarantees not to throw ConcurrentModificationException. This is because the returned iterator was just a snapshot of the list’s state when the iterator was constructed. So, this array never changes during the lifetime of the iterator, so any interference is not possible.

4. Package

An ArrayList class is included as part of Java java.util package, whereas CopyOnWriteArrayList class is part of the java.util.concurrent package.

Which implementation to use?

If a thread-safety is not required, an ArrayList should always be preferred over a CopyOnWriteArrayList since CopyOnWriteArrayList has the overhead of locking the list whether synchronization is required or not.

If a thread-safe implementation of ArrayList is required, we should use CopyOnWriteArrayList class.

That’s all about the differences between ArrayList and CopyOnWriteArrayList in Java.

 
Reference: ArrayList and CopyOnWriteArrayList Javadoc