CopyOnWriteArrayList in Java

What is CopyOnWriteArrayList

CopyOnWriteArrayList is a concurrent Collection class introduced in Java 5 Concurrent API. It implements List interface like ArrayList, Vector and LinkedList but it is a thread-safe collection and it achieves its thread-safety in a slightly different way than Vector or other thread-safe collection class. CopyOnWriteArrayList creates a fresh copy of the underlying array to implement all mutative operations like add, set etc. Creating a fresh copy is generally too expensive but may be more efficient than alternatives when traversal operations, i.e., iterations, vastly outnumber mutations, and is useful when you cannot or don’t want to synchronize traversals while accessing the List multiple concurrent threads. Iterator of CopyOnWriteArrayList is fail-safe and guaranteed not to throw ConcurrentModificationException. Element changing operations (add, remove, set) are not supported. So these operations will throw¬† UnsupportedOperationException.
CopyOnWriteArrayList vs ArrayList

1. CopyOnWriteArrayList is thread-safe and can be used in multi-threaded environment, whereas ArrayList is not thread-safe and cannot be used in multi-threaded environment.

2. Iterator of CopyOnWriteArrayList is fail-safe and does not throw ConcurrentModificationException but iterator of ArrayList is fail-fast and throws ConcurrentModificationException if modification is detected after iteration begins on ArrayList.

3. Remove operation on CopyOnWriteArrayList is not supported while remove operation on ArrayList is supported.

When should you use

You should only use this Collection to read when you are doing upwards of more than 90% reads becaue updating this Collection a lot will kill performance. If you try to sort a CopyOnWriteArrayList you will see the list throws an UsupportedOperationException (the sort operation invokes set on the collection N times).

Example

Output

Change the while loop as shown below, you will get the UnsupportedOperationException because remove operation on CopyOnWriteArrayList is not supported.

Output

Thanks for reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.