ConcurrentModificationException

ConcurrentModificationException

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
                                
                                    (24个答案)
                                
                        
                                2年前关闭。
            
                    
我有以下代码:

 Iterator<ggItem> iter = ggItemTimestampMap.keySet().iterator();
 ggItem gg;
 while (iter.hasNext()) {
        gg = iter.next();
        if (DateTime.now().isAfter(ggItemTimestampMap.get(gg).plusSeconds(10))) {
             Log.v("ggItem 10 second limit:", gg.toString());
             //If it hasn't been seen 10 seconds after its last timestamp. Remove it from the ArrayList and remove it from the ggItemTimeStampMap HashMap.
             ggItemTimestampMap.remove(gg); //TODO probable problem causer.
             removeggItemFromList(gg);
         }
 }


我在ConcurrentModificationException调用中收到iter.next();错误,不确定为什么吗?

我意识到您不能同时访问对象键和时间戳值的哈希图并同时对其进行修改,但是迭代器是否可以抵消它呢?

最佳答案

首先,您可以将HashMap更改为ConcurrentHashMap

其次,您可能尝试在类或对象上同步iter

synchronized(this) // if not in static context
{
    // synchronized body
}

synchronized(iter)
{
    // synchronized body
}


或在方法声明中使用

public synchronized void add(int value){
     this.count += value;
}



并解释了这个问题:

// @see http://stackoverflow.com/questions/602636/concurrentmodificationexception-and-a-hashmap
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
   Entry item = it.next();
   map.remove(item.getKey());
}


正确方法:

// @see http://stackoverflow.com/questions/602636/concurrentmodificationexception-and-a-hashmap
   Iterator it = map.entrySet().iterator();
   while (it.hasNext())
   {
      Entry item = it.next();
      it.remove(item);
   }


对于将来的麻烦,您需要知道ConcurrentModificationException的含义:


  当不允许对对象进行同时修改时,检测到该对象的同时修改的方法可能会引发此异常。

关于java - HashMap <Object,DateTime>中的ConcurrentModificationException ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31052455/

10-11 04:26