Search code examples
javathread-safetyconcurrentmodification

What is the best practice to prevent a sporadic ConcurrentModificationException in Java?


Which code sequence for iterating over a list or map prevent ConcurrentModificationException? We have repeatedly and sporadic ConcurrentModificationException in our code. There are 2 causes for the problem.

  1. Another thread change the list on iterating
  2. A method which is called in the loop is changing the list.

Problem 1 can be solved with a synchronized around the loop. But this is bad if alien code is called in the loop like cause 2.

Problem 2 can be solved with a copy of the list or map.

This means the list or map must be copy in a synchronized block before the loop. Are there a better solution?

Some sample code:

public void todoSomeThings( Map<Abc, Object> map ){
    for( Abc abc : map.keySet() ){
        abc.todoSomeThings();
    }
}

Solution

  • A fair warning: using j.u.c (java.util.concurrent) will remove the errors but you will be running into possibly worse case, i.e. race updates, stale reads, etc. The best practice is

    Know your data structures, use states... or at least (which is not best) use locks.