Behaviour of CopyOnWriteArrayList
Javadocs of CopyOnWriteArrayList
says
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.
I am confused now when will other threads see changes present in this fresh copy? Does this mean there will be number of copies of the underlying array equal to the number of mutations of the collection? If not so when are the changes of these individual copies are transferred to underlying array so that other threads can see them?
The idea here is that whenever you add or remove to the CopyOnWriteArrayList
, the underlying array is basically copied with the modification.
Does this mean there will be number of copies of the underlying array equal to the number of mutations of the collection
Yes, for every thread that updates the ArrayList
all other threads holding an older copy will in essence be referencing a different array.
when are the changes of these individual copies are transferred to underlying array so that other threads can see them?
An array you are looking at currently (lets say your iterator) will never change. When you read from an array you are reading it as it was when you started reading. If the CopyOnWriteArrayList
changes by another thread, the array you're currently observing will not be effected.
To get the most updated version do a new read like list.iterator();
That being said, updating this collection alot will kill performance. If you tried to sort a CopyOnWriteArrayList
you'll see the list throws an UsupportedOperationException
(the sort invokes set on the collection N times). You should only use this read when you are doing upwards of 90+% reads.
上一篇: 为什么静态变量被视为邪恶?