Say I have an array [a, b, c, d]
Thread A wants to add a new element e to the set. CopyOnWriteArrayList
creates new array, copies all values from the old array, adds new element e and then updates the reference to the new array with element e in it.
While thread A copies values, thread B also wants to add a new element f. So it copies all values without e adds f and then updates the reference to the array.
In this case the array may not have element e in it.
How thread safety is achieved here?
The CopyOnWriteArrayList was created to allow for the possibility of safe iterating over elements even when the underlying list gets modified.
CopyOnWriteArrayList is synchronized. ArrayList is not thread safe. CopyOnWriteArrayList is thread safe. ArrayList iterator is fail-fast and ArrayList throws ConcurrentModificationException if concurrent modification happens during iteration.
The remove(int index) method of CopyOnArrayList in Java is used to remove the element at the specified position in the list. Parameters: This method accepts a mandatory parameter index which specifies the position of the element. Return Type: This method returns the list after deleting the specified element.
All the modification methods (add
, set
, remove
, clear
, etc.) are guarded by locks. That's how you have the correct write ordering. However, because of the copy-on-write, that means that each of the backing arrays is effectively immutable, which means that read-only operations don't need locking. (The field holding the backing array is volatile
, so you still get the correct happens-before behaviour.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With