Deque类的Javadoc说:
这个类的迭代器方法返回的迭代器是快速失败的:如果在迭代器创建后的任何时候修改了deque,那么除了通过迭代器自己的remove方法之外,其他任何方式,迭代器通常都会抛出一个ConcurrentModificationException。因此,在并发修改的情况下,迭代器会迅速而干净地失败,而不是在未来某个未定的时间冒着任意的、不确定的行为的风险。
但是,以下程序的行为有所不同:
编辑我在粘贴整个代码时出错,“提交编辑的错误发生了”。呼!来吧。
// create an empty array deque with an initial capacity
Deque deque = new ArrayDeque(8);
// use add() method to add elements in the deque
deque.add(15);
deque.add(22);
deque.add(25);
deque.add(20);
System.out.println("printing elements using iterator:");
for(Iterator itr = deque.iterator();itr.hasNext();) {
System.out.println(itr.next());
deque.remove(); //deque is modifed after the iterator is created
}我原以为它会抛出ConcurrentModificationException,但它只是打印了以下输出:
printing elements using iterator:
15
22
25
20 知道为什么吗?
发布于 2015-04-21 11:02:56
看起来,这是因为在删除迭代器之前使用了它的第一个元素。如果您将代码更改为
for(Iterator itr = deque.iterator();itr.hasNext();) {
deque.remove();
System.out.println(itr.next());
}然后你就会看到例外。您最初的实现确实与文档相矛盾。
但是,在ArrayDeque的迭代器实现的实现中,next()方法有以下代码:
E result = (E) elements[cursor];
// This check doesn't catch all possible comodifications,
// but does catch the ones that corrupt traversal
if (tail != fence || result == null)
throw new ConcurrentModificationException();注意德克氏Javadoc中的以下段落
请注意,迭代器的快速失败行为不能保证,一般来说,在不同步并发修改的情况下不可能提供任何硬的保证。快速失败的迭代器在最大努力的基础上将ConcurrentModificationException抛出。因此,编写一个依赖于此异常的程序是错误的:迭代器的快速失败行为应该只用于检测bug。
https://stackoverflow.com/questions/29770055
复制相似问题