CopyOnWriteArrayList is a special purpose implementation of the List interface to better handle concurrency. It was introduced with Java 1.5 as a part of the java.util.concurrent package.
Why existing thread safe implementations aren't good enough?
Why existing thread safe implementations aren't good enough?
- synchronizedList from the Collections class locks the whole List which is bad performance as at any single point of time a single thread can access the collection
- the Vector implementation also has poor performance as thread safety is achieved by synchronizing all the methods of the class
Thread safety is handled in CopyOnWriteArrayList by making a copy of the underlying array whenever any mutation is performed (add, set, remove etc) in the list. This behavior is evident in the name of the collection as well. Now this brings us to the question if this list has costly affair or not as it makes copies for every change in the collection. The answer is YES and hence it's good for the cases where more read than write is performed.
Iterator behavoir
- Iterator and ListIterator from CopyOnWriteArrayList are fail-safe meaning that these iterators will not throw ConcurrentModificationException, making it thread safe
- these iterations use a reference to the state of the array at the point of iterator creation
- the array that the iterators point to never changes as any change in the collection results in a new array and hence, the changes in the collection are not visible through the iterator (making it the snapshot style iterator)
- these iterators do not support operations which alter the collection and any such operation results in UnsupportedOperationException
Comments