I encountered ConcurrentModificationException and by looking at it I can't see the reason why it's happening; the area throwing the exception and all the places modifying the collection are surrounded by
synchronized (this.locks.get(id)) {
...
} // locks is a HashMap<String, Object>;
I tried to catch the the pesky thread but all I could nail (by setting a breakpoint in the exception) is that the throwing thread owns the monitor while the other thread (there are two threads in the program) sleeps.
How should I proceed? What do you usually do when you encounter similar threading issues?
Having had to deal with similar issues I wrote a small helper to debug concurrent access situations on certain objects (sometimes using a debugger modifies the runtime behavior so much that the issue does not occur). The approach is similar to the one Francois showed, but a bit more generic. Maybe it helps someone: http://code.google.com/p/kongcurrent/
Sometime your application may be complex too complex and some functions may have too much side effect. Also, maybe another thread is really doing something wrong with that list and you can't find where easily.
For my own problem, I've write my own list system that delegates another list and, once locked, all other modifications throws ConcurrentModificationException, so the bad modification instruction will get at output with the exception. It can also detect errors described above.
Simply use it like this :
Hope it may help someone else.
if you need to delete few elements from your list. You can maintain another list like elements to be removed. And finally call removeAll(collection). Of course this is not good for huge data.
Similar to a previous post, you can get the same issue if you delete an entry. e.g.
Another common example is cleaning up a Map.
This particular problem can be resolved using an Iterator explicitly.
It may have nothing to do with the synchronization block.
ConcurrentModificationException
s often occur when you're modifying a collection while you are iterating over its elements.It's common to receive a ConcurrentModificationException when modifying a dynamic list while iterating over it (in a foreach-loop for example). You may want to make sure you're not doing that anywhere.