简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM