Reputation: 1398
I have the following code:
Map<String, List<String>> map;
for(String k : map.keySet()){
List<String> list = map.get(k);
boolean empty = list.isEmpty();//CME
if(!empty && somecheck(k, ...)){
list.clear();
}
}
And I'm getting ConcurrentModificationException
in isEmpty() method. List is an ArrayList
. There is no other threads modifying list, because it was created in this method before (and the all map too).
The only place modifying list is clear()
, but it called after isEmpty() and loop cannot execute on one list twice.
I'm using java 1.7
java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1169)
at java.util.ArrayList$SubList.size(ArrayList.java:998)
at java.util.AbstractCollection.isEmpty(AbstractCollection.java:86)
Upvotes: 4
Views: 945
Reputation: 3819
From the stacktrace you have given it appears the exception is being thrown in the sub-class implementing the SubList functionality - I assume the lists in your map are actually sublists of another list?
Presumably what is happening is that you are modifying the underlying list after you have created the sublist view (remember, a sublist is just a view onto another list - it does not take an independent copy).
Instead of putting sublists into the map, try taking a copy instead, for example:
map.put(key, new ArrayList(originalList.subList(start, end));
Upvotes: 6