Why is CopyOnWriteArrayList safe?

Say I have an array [a, b, c, d]

Theme A wants to add a new element e to the set. CopyOnWriteArrayList creates a new array, copies all the values ​​from the old array, adds a new e element, and then updates the link to the new array with the e element.

While thread A copies the values, thread B also wants to add a new element f . Thus, it copies all values ​​without e adds f , and then updates the array reference.

In this case, the array may not have an element e .

How is thread safe?

+5
source share
1 answer

All modification methods ( add , set , remove , clear , etc.) are protected by locks. This is how you have the correct recording order. However, due to copy-on-write, this means that each of the backup arrays is virtually unchanged, which means that read-only operations do not require locking. (The field that supports the swap array is volatile , so you still get the correct behavior - before the behavior.)

+9
source

Source: https://habr.com/ru/post/1201466/


All Articles