问题描述
我已经看了一下 ,似乎所有写入操作都受同一个锁的保护,读操作根本不受保护。据我了解,在JMM下,所有对变量(读和写)的访问都应该被锁定保护,否则可能会发生重新排序。
I've taken a look into OpenJDK source code of CopyOnWriteArrayList
and it seems that all write operations are protected by the same lock and read operations are not protected at all. As I understand, under JMM all accesses to a variable (both read and write) should be protected by lock or reordering effects may occur.
例如,$ code> set(int,E)方法包含这些行(在锁定下):
For example, set(int, E)
method contains these lines (under lock):
/* 1 */ int len = elements.length;
/* 2 */ Object[] newElements = Arrays.copyOf(elements, len);
/* 3 */ newElements[index] = element;
/* 4 */ setArray(newElements);
get(int)
另一方面,只有 return get(getArray(),index);
。
在我对JMM的理解,这意味着如果语句1-4被重新排序,如1-2(新)-4-2(copyOf)-3, get
可能会观察到数组处于不一致的状态。
In my understanding of JMM, this means that get
may observe the array in an inconsistent state if statements 1-4 are reordered like 1-2(new)-4-2(copyOf)-3.
我不明白JMM是否明白了,或者有什么其他解释为什么 CopyOnWriteArrayList
是线程安全的?
Do I understand JMM incorrectly or is there any other explanations on why CopyOnWriteArrayList
is thread-safe?
推荐答案
如果您查看底层数组引用,您将看到它被标记为 volatile
。当写操作发生时(如上面的提取),这个 volatile
引用仅在最终语句中通过 setArray
。直到这一点,任何读取操作将从数组的旧版本返回元素。
If you look at the underlying array reference you'll see it's marked as volatile
. When a write operation occurs (such as in the above extract) this volatile
reference is only updated in the final statement via setArray
. Up until this point any read operations will return elements from the old copy of the array.
重要的是,数组update是一个原子操作,因此读取将始终看到数组处于一致的状态。
The important point is that the array update is an atomic operation and hence reads will always see the array in a consistent state.
仅提取写入操作锁的优点得到改进读取的吞吐量:这是因为 CopyOnWriteArrayList
的写入操作可能会非常慢,因为它们涉及复制整个列表。
The advantage of only taking out a lock for write operations is improved throughput for reads: This is because write operations for a CopyOnWriteArrayList
can potentially be very slow as they involve copying the entire list.
这篇关于CopyOnWriteArrayList如何线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!