CopyOnWriteArrayList
Is a synchronised datastructure to support to use ArrayList
concurrently.
When add
, the array will always create a copy of the existing array and do modification on the copy, and then we finally update the volatile reference to the original array. That's why we name it "CopyOnWriteArrayList".
For get
, it will always iterate through the non-modified list so that it's safe to do so
CopyOnWriteArrayList<Integer> numbers
= new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8});
Iterator<Integer> iterator = numbers.iterator();
numbers.add(10);
When looping through the iterator, we only see 1, 3, 5, 8
.
[!note]
Due to the natural of copying, removing usingIterator.remove()
is not supported.
Use case
CopyOnWriteArrayList
is suitable when the rate of writing is less than the rate of reading. Because copy the whole array on write is very expensive.
One of the particular usecase is it can be use in event-dispatching system where we need to loop through the list of listeners where registering or de-registering the listener happens rarely.