尽管使用了同步的 ConcurrentModificationException [英] ConcurrentModificationException despite using synchronized

查看:24
本文介绍了尽管使用了同步的 ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 public synchronized X getAnotherX(){ 
  if(iterator.hasNext()){
   X b = iterator.next();
   String name = b.getInputFileName();
  ...
   return b;
  }
  else{return null;}
 }

尽管声明头中有synchronized 语句,我仍然在使用iterator.next() 的那一行得到一个ConcurrentModificationException 异常;怎么了?

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 通常与多线程无关.大多数情况下,它发生是因为您正在修改它在迭代循环体内迭代的集合.例如,这会导致:

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);
    }
}

在这种情况下,您必须改用 iterator.remove() 方法.如果您要添加到集合中,这同样会发生,在这种情况下,没有通用的解决方案.但是,如果处理列表并且它具有 add() 方法,则可以使用子类型 ListIterator.

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屋!

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