Java:ConcurrentModificationException迭代列表[重复]

问题描述 投票:8回答:3

当我执行以下代码时,我得到ConcurrentModificationException

 Collection<String> myCollection = Collections.synchronizedList(new ArrayList<String>(10));
    myCollection.add("123");
    myCollection.add("456");
    myCollection.add("789");
    for (Iterator it = myCollection.iterator(); it.hasNext();) {
        String myObject = (String)it.next();
        System.out.println(myObject);
        myCollection.remove(myObject); 
        //it.remove();
    }

为什么我得到异常,即使我使用Collections.synchronizedList?

当我将myCollection更改为

  ConcurrentLinkedQueue<String> myCollection = new ConcurrentLinkedQueue<String>();

我没有得到那个例外。

java.util.concurrent中的ConcurrentLinkedQueue与Collections.synchronizedList有何不同?

java collections
3个回答
13
投票

同步列表将不提供Iterator的新实现。它将使用同步列表的实现。 implementationiterator()是:

public Iterator<E> iterator() {
   return c.iterator(); // Must be manually synched by user! 
}

来自ArrayList

这个类的iterator和listIterator方法返回的迭代器是快速失败的:如果在创建迭代器之后的任何时候对列表进行结构修改,除了通过迭代器自己的remove或add方法之外,迭代器将抛出一个ConcurrentModificationException

来自ConcurrentLinkedQueue#iterator

以适当的顺序返回此队列中元素的迭代器。返回的迭代器是一个“弱一致”的迭代器,它永远不会抛出ConcurrentModificationException,并保证在构造迭代器时遍历元素,并且可能(但不保证)反映构造之后的任何修改。

两个集合返回的迭代器在设计上是不同的。


7
投票

不要这样做

myCollection.remove(myObject); 

it.remove();

无需同步或并发收集


2
投票

java.util.concurrent中的ConcurrentLinkedQueue与Collections.synchronizedList有何不同?

它们具有不同的实现,因此可以选择是抛出ConcurrentModificationException,还是处理您优雅描述的情况。显然CLQ处理得很好,并且由Collections.synchronizedList包装的ArrayList(我的猜测是行为是ArrayList的,而不是包装器的)不会。

正如@unbeli所说,通过迭代器删除,而不是迭代时的集合。

© www.soinside.com 2019 - 2024. All rights reserved.