4

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)
4
  • 2
    is that map getting filled in another thread? Commented May 31, 2017 at 10:00
  • what is "if(list)" check supposed to do and how does it compile? Please provide stackoverflow.com/help/mcve Commented May 31, 2017 at 10:00
  • @ΦXocę웃Пepeúpaツ As i said, map created in this method. Commented May 31, 2017 at 10:05
  • @OlegEstekhin old null check, misstyped. Commented May 31, 2017 at 10:06

1 Answer 1

6

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));
Sign up to request clarification or add additional context in comments.

2 Comments

Good sleuthing!
Perhaps, the list values in that map are all sublists of the same source list, so when clear() is invoked on one of them during in the loop, calling isEmpty() on one of the others in the next iteration will fail…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.