gpt4 book ai didi

java - 同步集合中的 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-11-30 02:30:17 24 4
gpt4 key购买 nike

我正在使用SynchronizedCollection.containsAll,面临的问题是当我运行以下代码时,我收到ConcurrentModification Exception

根据我的理解,代码应该毫无异常地终止。

public class Main {

public static void main(String[] args) {
List l1 = new LinkedList(), l2 = new LinkedList();
for (int i = 0; i < 100000; i++) {
l1.add("" + i);
}
for (int i = 0; i < 100000; i++) {
l2.add("" + i);
}
// reverse to make the search take a little longer
Collections.reverse(l2);
final List sl1 = Collections.synchronizedList(l1);
final List sl2 = Collections.synchronizedList(l2);

new Thread() {
public void run() {
// synchronized (sl2) {
sl1.containsAll(sl2);
// }
}
}.start();
new Thread() {
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
sl2.add("3");
}
}.start();
}

}

有人可以帮助我理解为什么我会遇到这个异常吗?

最佳答案

根据 the documentation of Collections::synchronizedList

It is imperative that the user manually synchronize on the returned list when iterating over it.

在您的示例中,当您运行 sl.containsAll(sl2) 时,您会迭代 sl2,而不在 sl2 上进行同步。诚然,这是 containsAll 方法的实现细节,但是 it is clearly indicated in the javadoc :

This implementation iterates over the specified collection, checking each element returned by the iterator in turn to see if it's contained in this collection.

您可以通过在 sl2 上同步来解决该问题(即取消注释您已注释掉的代码)。

关于java - 同步集合中的 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44453894/

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