Reputation: 765
The source code is here:
public E set(int index, E element) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
E oldValue = get(elements, index);
if (oldValue != element) {
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len);
newElements[index] = element;
setArray(newElements);
} else {
// Not quite a no-op; ensures volatile write semantics
setArray(elements);
}
return oldValue;
} finally {
lock.unlock();
}
}
But I think the if-else
block could be more concise as following:
if (oldValue != element) {
elements[index] = element;
}
Please help me with this, thanks in advance.
Upvotes: 1
Views: 191
Reputation: 3836
CopyOnWriteArrayList creates new array instance in any mutator method to ensure that Iterator will always use "snapshot" of underlying array data which is actual to the moment of Iterator creation. It prevents ConcurrentModificationException, but some values can become outdated (deleted elements for example)
Upvotes: 1
Reputation: 533530
As the class name suggests, this class performs a copy-on-write of the underlying data structure i.e. the array.
Whenever you modify the array, you need to take a copy. If you modify the existing array, other functions such as Iterating may not behave as expected.
Upvotes: 2