迭代器但仍然是ConcurrentModificationException

时间:2015-09-25 20:27:35

标签: java arraylist iterator concurrentmodification concurrentskiplistmap

所有

遇到ConcurrentModificationException问题并努力寻找解决方案,部分原因是我无法在迭代时看到我修改列表的位置...任何想法?我已经突出显示导致问题的那一行(it3.remove())。真的处于停滞状态......

编辑:Stacktrace:

Exception in thread "Thread-4" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at com.shimmerresearch.advancepc.InternalFrameAndPlotManager.subtractMaps(InternalFrameAndPlotManager.java:1621)

第1621行对应于上面引用的代码中的it3.remove()。

private void subtractMaps(ConcurrentSkipListMap<String, PlotDeviceDetails> firstMap, ConcurrentSkipListMap<String, PlotDeviceDetails> secondMap) {

    // iterate through the secondmap
    Iterator<Entry<String, PlotDeviceDetails>> it1 = secondMap.entrySet().iterator();
    while (it1.hasNext()) {
        Entry<String, PlotDeviceDetails> itEntry = (Entry) it1.next();
        String mapKey = (String) it1Entry.getKey();
        PlotDeviceDetails plotDeviceDetails = (PlotDeviceDetails)it1Entry.getValue();

        // if we find an entry that exists in the second map and not in the first map continue
        if(!firstMap.containsKey(mapKey)){
            continue;
        }

         // iterate through a list of channels belonging to the secondmap
        Iterator <PlotChannelDetails> it2 = plotDeviceDetails.mListOfPlotChannelDetails.iterator(); 
        while (it2.hasNext()) {
            PlotChannelDetails it2Entry = it2.next();

            // iterate through a list of channels belonging to the firstmap
            Iterator <PlotChannelDetails> it3 = firstMap.get(mapKey).mListOfPlotChannelDetails.iterator();
            innerloop:
            while(it3.hasNext()){
                // if a channel is common to both first map and second map, remove it from firstmap
                PlotChannelDetails it3Entry = it3.next();
                if(it3Entry.mChannelDetails.mObjectClusterName.equals(it2Entry.mChannelDetails.mObjectClusterName)){
                    it3.remove(); // this line is causing a concurrentModificationException
                    break innerloop;
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

plotDeviceDetails.mListOfPlotChannelDetailsfirstMap.get(mapKey).mListOfPlotChannelDetails引用了相同的列表。

plotDeviceDetailsfirstMap.get(mapKey)是否也引用相同的对象是未知的,但没有更多信息,但它们共享频道列表。

答案 1 :(得分:1)

堆栈跟踪显示mListOfPlotChannelDetailsArrayList,并且由于堆栈跟踪也显示错误来自it3.remove(),并且代码中没有任何内容可以因此,您真正面临并发修改,即另一个线程已更新ArrayListit3迭代。

请记住,ArrayList 支持并发多线程访问。