I get ConcurrentModificationException
when iterating an ArrayList
and adding objects to a secondary ArrayList
. I don't really know why because I'm not editing the list that I'm iterating through.
This happens in two parts of my code. These are the codes.
EDIT - Code 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());
}
}
In Code 1 above, should I copy the historicalIndexList like this:
ArrayList<HistoricalIndex> historicalIndexList = new ArrayList<HistoricalIndex>(IndexService.historicalIndexesMap.get(id));
instead of doing this: ?
ArrayList<HistoricalIndex> historicalIndexList = IndexService.historicalIndexesMap.get(id);
Code 2:
List<Double> tmpList = new ArrayList<Double>();
for(HistoricalIndex hi : list){ //EXCEPTION HERE
tmpList.add(hi.getIndex());
}
Does anyone have a clue why this happens?
Stacktrace:
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