简体   繁体   English

迭代优先级队列引发ConcurrentModificationException

[英]iterating priority queue throws ConcurrentModificationException

PriorityQueue<Integer> queue = new PriorityQueue<Integer>(4);
queue.add(8);
queue.add(5);
queue.add(23);
queue.add(6);
for(int i:queue)
   System.out.println(queue.remove());

The preceding code throws ConcurrentModificationException. 前面的代码引发ConcurrentModificationException。 I don't see any threads of modifying the priority queue. 我看不到任何修改优先级队列的线程。 I do understand it is unsynchronized collection as well. 我确实知道它也是不同步的集合。 I am running Ubuntu 12.10 with Oracle Java SDK 6.0. 我正在使用Oracle Java SDK 6.0运行Ubuntu 12.10。
This problem looks lot interesting. 这个问题看起来很有趣。 Can somebody give an explanation? 有人可以解释一下吗? Is it a defect? 这是缺陷吗?

YOU SHOULD ONLY USE ITERATOR.remove() method .It is the only method that guarantee that you do not have a ConcurrentModificationException 您仅应使用ITERATOR.remove()方法。这是唯一确保您没有ConcurrentModificationException的方法。

There is only one thread.But when you iterate with for each you actually modify the queue by removing elements from it so you actually will eventually modify the queue at a different step then you want. 只有一个线程,但是当您对每个线程进行迭代时,实际上是通过从队列中删除元素来修改队列的,因此实际上您最终将在所需的其他步骤修改队列。

When you Iterate over any collection, you can only use Iterator.remove() to remove entries safely for that iterator (and no other) This is a know gotcha which has been around since Java 1.2 when Iterator was introduced. 对任何集合进行迭代时,只能使用Iterator.remove()安全地删除该迭代器的条目(不能删除其他条目)。这是自Java 1.2引入迭代器以来就已经存在的已知问题。

Note: The Concurrent collections maintain "weak consistency" which allows you to iterate over the collection while it is being modified. 注意:并发集合保持“弱一致性”,这使您可以在修改集合时对其进行迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM