了解 CopyOnWriteArrayList 迭代器行为
Understanding CopyOnWriteArrayList iterator behavior
我正在学习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.
我期待一个无限循环,因为 "actions in a thread prior to placing an object into a CopyOnWriteArrayList happen-before actions subsequent to the access or removal"。
但是我的控制台输出是:
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 循环开始时打印列表中的元素,因为正是在该时刻创建了迭代器。
我正在学习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.
我期待一个无限循环,因为 "actions in a thread prior to placing an object into a CopyOnWriteArrayList happen-before actions subsequent to the access or removal"。
但是我的控制台输出是:
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 循环开始时打印列表中的元素,因为正是在该时刻创建了迭代器。