gpt4 book ai didi

java - 循环中是否存在ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-01 18:03:44 25 4
gpt4 key购买 nike

我在下面有一个片段代码。我有 2 个线程 A 和 B 同时运行。

List<String> listPeople = new ArrayList<>();
// Add more item
.....

Thread A
for (String item : listPeople) {
System.out.println("Name is: " + item.name);
}

Thread B
- add/remove item to list people

使用这种形式的 for 循环,它通过 List 的迭代器进行循环。那么它会因 ConcurrentModificationException 崩溃吗?

最佳答案

来自ConcurrentModificationException Javadoc :

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. [...]

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

关于java - 循环中是否存在ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38559449/

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