CopyOnWriteArrayList 假设在迭代器的迭代中是不会修改这个 list 的,如果你在迭代过程中通过迭代器去修改它(Iterator iter ... iter.set(xxx))就会出现这个异常。它工作时,修改的操作仅发生在 List 中定义的方法,如果你想在它的迭代器中也修改它,那还是需要同步的。
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. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException.看后面的解释,对iterator的修改貌似也是不支持或不会反映到iterator上的,这个层面来讲应该是安全的,不知道lz能不能还原一小段模拟程序,类似如下: public static void main(String[] args) { CopyOnWriteArrayList<Integer> cowal = new CopyOnWriteArrayList<Integer>(); cowal.add(1); cowal.add(2); cowal.add(3); List<Integer> sub = cowal.subList(1, 2); cowal.add(4); sub.get(0); // throws ConcurrentModificationException }
public static void main(String[] args) {
CopyOnWriteArrayList<Integer> cowal = new CopyOnWriteArrayList<Integer>();
cowal.add(1);
cowal.add(2);
cowal.add(3); List<Integer> sub = cowal.subList(1, 2);
cowal.add(4);
sub.get(0); // throws ConcurrentModificationException
}