我正在研究 CopyOnWriteArrayList
,下面的情况让我开始思考。
我的主要方法是这样的:
public static void main(String[] args) {
List<String> list = new CopyOnWriteArrayList<String>();
list.add("Init1");
list.add("Init2");
list.add("Init3");
list.add("Init4");
for(String str : list){
System.out.println(str);
list.add("PostInit");
}
}
在我阅读的 javadoc 中:
Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a CopyOnWriteArrayList happen-before actions subsequent to the access or removal of that element from the CopyOnWriteArrayList in another thread.
我期待一个无限循环,因为 “在将对象放入 CopyOnWriteArrayList 之前线程中的操作发生在访问或删除之后的操作之前”。
但是我的控制台输出是:
Init1
Init2
Init3
Init4
我相信,我在这里缺乏一些理解。有人可以帮忙吗?
最佳答案
来自文档
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
for-each 循环使用迭代器,参见 https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2 .
因此,for-each 循环将在 for 循环开始时打印列表中的元素,因为它是在创建迭代器的那一刻。
关于java - 了解 CopyOnWriteArrayList 迭代器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57389068/