I have a lot of confusion about Java’s CopyOnWriteArrayist. I know, when we have a modification on it like update, insert of set, it will lock the whole list, copy out a total copy of the source list, do the modification and then release the lock. So, My question is:
-
When doing the modification, why cannot we just lock the array, do the modification and finally release the lock? Why we have to make a new copy of the array?
-
The write lock is only effective for a concurrent modification, but not for a modification and read. When we are doing a read, we read from the old array and get the old data, right?
1.When doing the modification, why cannot we just lock the array, do the modification and finally release the lock? Why we have to make a new copy of the array?
Because if you were to lock on write and don’t create a new copy you will also have to lock on read which would be a bottleneck. You can have this functionality with Collections.synchronizedList(list)
. With CopyOnWriteArrayList
there is no lock on read, which means is faster. Because of this CopyOnWriteArrayList
is only useful when you have few updates and inserts and many concurrent reads.
2.The write lock is only effective for a concurrent modification, but not for a modification and read. When we are doing a read, we read from the old array and get the old data, right?
Yes. If you are iterating over the CopyOnWriteArrayList
and while iterating a write is made concurrently, then your Iterator
is not aware of the changes. You’ll have to start iterating again after the update, to have the latest data.