Home » Core Java » CopyOnWriteArrayList in Java

CopyOnWriteArrayList in Java

CopyOnWriteCopyOnWriteArrayList & its feature ::
1.  CopyOnWriteCopyOnWriteArrayList class is another important class of Collection framework.
2.  CopyOnWriteArrayList was intoduced in java 1.5 version inside java.util.concurrent package.
3.  CopyOnWriteArrayList implements generic List, RandomAccess, Cloneable and java.io.Serializable
4.  CopyOnWriteArrayList is a thread-safe variant of java.util.ArrayList in which all mutative operations add(), remove() etc. are implemented by making a fresh copy of the underlying array.
5.  CopyOnWriteArrayList can accept any element including multiple null values.
6.  CopyOnWrite means, a copy of the whole list is made each time you write to the list such as adding an element or remove an element.So, CopyOnWriteArrayList is ordinarily too costly. But if you have very less add() or remove() method and more traversal in your requirement you can use thread safe conurrency utility CopyOnWriteArrayList.
7. CopyOnWriteArrayList uses Iterator interface to traverse the elements.While traversing the elements using iterator if the structure of the CopyOnWriteArrayList is modified using add or remove method ,iterator does not throw ConcurrentModificationException.So iterators for CopyOnWriteArrayList are fail-safe.
8. CopyOnWriteArrayList throws UnsupportedOperationException if iterator.remove() method is called while traversing the CopyOnWriteArrayList using iterator.
9. The “snapshot” style iterator method for CopyOnWriteArrayList uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators such as remove() is not supported. This methods throws UnsupportedOperationException.
Program ::

Output ::

Example of UnsupportedOperationException on CopyOnWriteArrayList ::

Output ::

Reference ::


Leave a comment

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

five × 2 =