当我执行以下代码时,我得到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();
}
Run Code Online (Sandbox Code Playgroud)
为什么我得到异常,即使我使用Collections.synchronizedList?
当我将myCollection更改为
ConcurrentLinkedQueue<String> myCollection = new ConcurrentLinkedQueue<String>();
Run Code Online (Sandbox Code Playgroud)
我没有得到那个例外.
java.util.concurrent中的ConcurrentLinkedQueue与Collections.synchronizedList有何不同?
And*_*s_D 13
一个同步列表将不会提供新的实现Iterator.它将使用同步列表的实现.该执行的iterator()就是:
public Iterator<E> iterator() {
return c.iterator(); // Must be manually synched by user!
}
Run Code Online (Sandbox Code Playgroud)
来自ArrayList:
这个类的iterator和listIterator方法返回的迭代器是快速失败的:如果在创建迭代器之后的任何时候对列表进行结构修改,除了通过迭代器自己的remove或add方法之外,迭代器将抛出一个
ConcurrentModificationException
来自ConcurrentLinkedQueue#iterator:
以适当的顺序返回此队列中元素的迭代器.返回的迭代器是一个"弱一致"的迭代器,它永远不会抛出
ConcurrentModificationException,并保证遍历构造迭代器时存在的元素,并且可能(但不保证)反映构造之后的任何修改.
两个集合返回的迭代器在设计上是不同的.
不要这样做
myCollection.remove(myObject);
Run Code Online (Sandbox Code Playgroud)
做
it.remove();
Run Code Online (Sandbox Code Playgroud)
无需同步或并发收集
| 归档时间: |
|
| 查看次数: |
11816 次 |
| 最近记录: |