Reputation: 1717
According to javadoc of CopyOnWritearrayList
:
A thread-safe variant of
ArrayList
in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array
but I want to know why its making the fresh copy each time as it is doing this operation in the exclusive lock.
Upvotes: 2
Views: 182
Reputation: 72854
Even if the list locks on mutative operations, one could still get an Iterator
and loop over the collection, which is not synchronized. The fresh copy created by these mutative operations will not be seen by the iterator. This allows other threads to read from the list without worrying about exceptions due to modifications of the list, as mentioned in the Javadocs:
The "snapshot" style iterator method 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
Upvotes: 4