Java:在迭代列表时发生ConcurrentModificationException [英] Java : ConcurrentModificationException while iterating over list

查看:188
本文介绍了Java:在迭代列表时发生ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行下面的代码,我得到ConcurrentModificationException

When I execute the following code, I get 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?

Why am I getting the exception, even though I am using Collections.synchronizedList?

当我将myCollection改为

When I change myCollection to

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

我没有这个异常。

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

How is ConcurrentLinkedQueue in java.util.concurrent different from Collections.synchronizedList ?

推荐答案

> List将不提供 Iterator 的新实现。它将使用 synchronized 列表的实现。 的实现

A synchronized List will does not provide a new implementation of Iterator. It will use the implementation of the synchronized list. The implementation of iterator() is:

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

ArrayList


此类的迭代器和listIterator方法返回的迭代器 fail-fast :如果结构修改列表在创建迭代器之后的任何时候,除了通过迭代器自己的remove或add方法,迭代器将抛出一个 ConcurrentModificationException

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException

ConcurrentLinkedQueue#iterator


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

Returns an iterator over the elements in this queue in proper sequence. The returned iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

两个集合返回的迭代器根据设计不同

The iterators returned by the two collections are different by design.

这篇关于Java:在迭代列表时发生ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆