【发布时间】:2015-01-07 11:50:03
【问题描述】:
当迭代ArrayList 并将对象添加到辅助ArrayList 时,我得到ConcurrentModificationException。我真的不知道为什么,因为我没有编辑我正在迭代的列表。
这发生在我的代码的两个部分。这些是代码。
编辑 - 代码 1:
public static ConcurrentHashMap<Long, ArrayList<HistoricalIndex>> historicalIndexesMap = new ConcurrentHashMap<Long, ArrayList<HistoricalIndex>>();
ArrayList<HistoricalIndex> historicalIndexList = IndexService.historicalIndexesMap.get(id);
List<Double> tmpList = new ArrayList<Double>();
for(HistoricalIndex hi : historicalIndexList){ //EXCEPTION HERE
if((System.currentTimeMillis()-hi.getTimestamp()) >= ONE_MINUTE){
tmpList.add(hi.getIndex());
}
}
在上面的代码 1 中,我应该像这样复制historyIndexList:
ArrayList<HistoricalIndex> historicalIndexList = new ArrayList<HistoricalIndex>(IndexService.historicalIndexesMap.get(id));
而不是这样做:?
ArrayList<HistoricalIndex> historicalIndexList = IndexService.historicalIndexesMap.get(id);
代码 2:
List<Double> tmpList = new ArrayList<Double>();
for(HistoricalIndex hi : list){ //EXCEPTION HERE
tmpList.add(hi.getIndex());
}
有人知道为什么会这样吗?
堆栈跟踪:
21:19:50,426 ERROR [stderr] (pool-9-thread-6) java.util.ConcurrentModificationException
21:19:50,429 ERROR [stderr] (pool-9-thread-6) at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
21:19:50,432 ERROR [stderr] (pool-9-thread-6) at java.util.ArrayList$Itr.next(ArrayList.java:831
【问题讨论】:
-
list是什么类型,在哪里定义? -
你确定historyIndexList没有被任何其他线程修改过吗?
-
典型的并发问题/竞争条件。
-
@nfechner 列表是 ArrayList 类型,它在
ConcurrentHasmap中定义。使用此列表的每个线程在从 hashmap 中获取它后将其复制到一个临时列表中。 -
在循环中添加日志语句并检查打印出的线程
标签: java arraylist concurrentmodification