gpt4 book ai didi

java - Deque 删除不会引发 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-01 11:38:21 24 4
gpt4 key购买 nike

Deque 类'Javadoc说:

The iterators returned by this class's iterator method are fail-fast: If the deque is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will generally throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

但是,以下程序的行为有所不同:

[编辑]:我在粘贴整个代码时遇到错误“提交编辑时发生错误”。哇!来吧,SO。

// 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

知道为什么吗?

最佳答案

看起来这是因为您在删除迭代器之前消耗了它的第一个元素。如果您将代码更改为

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();

请注意 Deque's Javadoc 中的以下段落:

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

关于java - Deque 删除不会引发 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29770055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com