user2916610
user2916610

Reputation: 765

Why set(int index, E element) function in CopyOnWriteArrayList is so fussy?

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

Answers (2)

Cootri
Cootri

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

Peter Lawrey
Peter Lawrey

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

Related Questions