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.
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();
}
}
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.