ConcurrentModificationException,尽管使用同步 [英] ConcurrentModificationException despite using synchronized
问题描述
public synchronized X getAnotherX(){
if(iterator.hasNext()){
X b = iterator.next
String name = b.getInputFileName();
...
return b;
}
else {return null;}
}
在声明头的synchronized语句,我仍然得到一个ConcurrentModificationException异常在行,我使用iterator.next();这里有什么问题?
ConcurrentModificationException
通常与多个线程无关。大多数情况下,它发生,因为你正在修改它在迭代循环体内迭代的集合。例如,这将导致:
迭代器迭代器= collection.iterator
while(iterator.hasNext()){
Item item =(Item)iterator.next();
if(item.satisfiesCondition()){
collection.remove(item);
}
}
在这种情况下,您必须改用 iterator.remove()
方法。如果要添加到集合,这种情况同样发生,在这种情况下没有一般解决方案。但是,如果处理一个列表并且有一个 add()
方法,则可以使用 ListIterator
p>
public synchronized X getAnotherX(){
if(iterator.hasNext()){
X b = iterator.next();
String name = b.getInputFileName();
...
return b;
}
else{return null;}
}
despite the synchronized statement in the declaration header, i still get a ConcurrentModificationException Exception at the line where i use iterator.next(); whats wrong here ?
ConcurrentModificationException
usually has nothing to do with multiple threads. Most of the time it occurs because you are modifying the collection over which it is iterating within the body of the iteration loop. For example, this will cause it:
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
Item item = (Item) iterator.next();
if (item.satisfiesCondition()) {
collection.remove(item);
}
}
In this case you must use the iterator.remove()
method instead. This occurs equally if you are adding to the collection, in which case there is no general solution. However, the subtype ListIterator
can be used if dealing with a list and this has an add()
method.
这篇关于ConcurrentModificationException,尽管使用同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!