[英]Concurrent Modification Exception thrown by .next from Iterator
Not sure exactly what's wrong here: 不确定这里究竟出了什么问题:
while(itr.hasNext())
{
Stock temp =itr.next();
}
This code is throwing a ConcurrentModificationException at itr.next(); 此代码在itr.next()中抛出ConcurrentModificationException;
Initialization for the iterator is private Iterator<Stock> itr=stockList.iterator();
迭代器的初始化是
private Iterator<Stock> itr=stockList.iterator();
Any ideas? 有任何想法吗?
[The basic code was copied directly from professor's slides] [基本代码直接从教授的幻灯片中复制]
This could be happening because of two reasons. 这可能是因为两个原因而发生的。
The below codes could cause ConcurrentModificationException 以下代码可能导致ConcurrentModificationException
Iterator<Stock> itr = stockList.iterator();
while(itr.hasNext())
{
Stock temp = itr.next();
stockList.add(new Stock()); // Causes ConcurrentModificationException
stockList.remove(0) //Causes ConcurrentModificationException
}
Some other thread is modifying the underlying collection? 其他一些线程正在修改底层集合? I suspect that there is code above what you are showing us that causes the problem: a mod to the collection between the call to iterator() and the loop.
我怀疑上面有代码,而不是你向我们展示的导致问题的代码:调用iterator()和循环之间的集合的mod。
Most plausible reason is that some code has modified the underlying collection after you obtained your iterator. 最合理的原因是一些代码在您获得迭代器后修改了底层集合。
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.
此类的iterator和listIterator方法返回的迭代器是快速失败的:如果在创建迭代器之后的任何时候对列表进行结构修改,除了通过迭代器自己的remove或add方法之外,迭代器将抛出ConcurrentModificationException。 Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
因此,在并发修改的情况下,迭代器快速而干净地失败,而不是在未来的未确定时间冒着任意的,非确定性行为的风险。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.