使用Iterator和Vector的未知并发修改异常java

时间:2012-09-17 19:33:56

标签: java concurrency iterator concurrent-programming

我不断获得并发修改例外

String[] permsList = Constants.CUST_MKT_PERMS_FIELDS;
String hiddenFieldVector = new Vector<String>(permsList.length);
Iterator<String> itr = hiddenFieldVector.iterator();

for(int i = 0; i < arrayLength; i++){    //arrayLength is never null or 0

    ...a lot of code...
    String target = fromDatabase();     //this is never null

   while(itr.hasNext() && hiddenFieldVector.contains(target)){
    hiddenFieldVector.remove(target);
    Logger.debug("itr.next() = " + itr.next());
   }

    ...a lot of code...
}

任何想法为什么?

目前的解决方案:

while(itr.hasNext() && hiddenFieldVector.contains(target) && (itr.next().equals(target))){
                        itr.remove();
                        Logger.debug("itr.next() = " + itr.next());
                    }

1 个答案:

答案 0 :(得分:6)

hiddenFieldVector.remove(target);

循环播放时,请勿在{{1​​}}上致电remove。循环时修改列表会抛出list

使用ConcurrentModificationException并在iterator而不是remove上致电iterator

示例:

list