I have few issues in understanding this concept. Please correct me where I am wrong.
Basically, iteration makes a snapshot (copy) of original array, thus threads that modify collection won't affect our iteration because iteration uses a copy. So no ConcurrentException here, nice.
But then I also read that any modification is done by making a copy of original collection and using that copy to make changes. Then it sets it to original one.
Can someone tell me why is there need to make a copy when modifying, when iteration already uses its own copy. Why have 2 copes, one for read, one for write?
I think I said something incorrect, so please can you point what am I missing?
When CopyOnWriteArrayList
creates an iterator, the "snapshot" is a reference to its current array - not a copy of the array.
The iterator can use a reference to the array because the array is never modified. CopyOnWriteArrayList
does that the name says: it makes a new copy of the array when anything is changed. If some iterator using the old array at the same time, that's not a problem, the iterator will just keep using the old array and it will not see any of the modifications made to the list. This makes the iterator "weakly consistent."