Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is CopyOnWriteArrayList safe?

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?

like image 897
user1745356 Avatar asked Aug 30 '14 11:08

user1745356


People also ask

Why do we use CopyOnWriteArrayList?

The CopyOnWriteArrayList was created to allow for the possibility of safe iterating over elements even when the underlying list gets modified.

What is difference between ArrayList and CopyOnWriteArrayList?

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.

How do I get rid of CopyOnWriteArrayList?

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.


1 Answers

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.)

like image 81
Chris Jester-Young Avatar answered Oct 03 '22 02:10

Chris Jester-Young