gpt4 book ai didi

java - CopyOnWriteArrayList 如何用副本替换原始数组以及何时发生?

转载 作者:行者123 更新时间:2023-12-02 11:16:36 26 4
gpt4 key购买 nike

根据 CopyOnWriteArrayList JavaDoc:

A thread-safe variant of java.util.ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

每个线程在突变之后总是在自己的本地副本上工作吗?

我认为副本应该替换原始数组。如何用原始数组替换副本以供其他线程使用?这发生在什么阶段?

最佳答案

如果您查看 set 实现,它会使用现有元素创建新的对象数组,并在操作后替换新数组

/**
* Replaces the element at the specified position in this list with the
* specified element.
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
synchronized (lock) {
Object[] elements = getArray();//creating the new array with ting vaue
E oldValue = elementAt(elements, index);

if (oldValue != element) {
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len);
newElements[index] = element;
setArray(newElements);//replacing the old array
} else {
// Not quite a no-op; ensures volatile write semantics
setArray(elements);
}
return oldValue;
}
}

以相同的方式实现添加和删除方法因为所有这些方法都是线程安全的,所以假设如果两个线程在 add 方法上工作,那么两个线程都有自己的元素副本

来自文档:

The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. The iterator will not reflect additions, removals, or changes to the list since the iterator was created.

关于java - CopyOnWriteArrayList 如何用副本替换原始数组以及何时发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50226016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com