Re: ConcurrentModificationException
Andy Chambers wrote:
Hi,
This seems to be a bit of a FAQ but I can't see how the usual answers
apply in this case. As I understand it, this exception gets thrown
either when another thread tries to modify an Iterator's collection,
or when some other code attempts to modify a collection whilst an
iterator on it is "alive".
In my case, the exception is only thrown when the program is run (i.e.
it doesn't happen inside the debugger). On inspecting the stack
trace, I can't see any calls to add/remove/update any underlying
collection. Finally, the problem has arisen with a move to Java 1.6;
we didn't get these exceptions with 1.42.
I fixed one instance of the problem by putting the offending code
inside a synchronized block. However, this just resulted in hitting
another instance.
Does anyone have any pointers on how I can track down the cause and
fix these?
The general description strongly suggests a timing problem, related to
access to the underlying collection from more than one thread. Either
using a debugger or changing JVM implementation could change relative
timings of threads.
The fact that adding synchronization changed the symptoms tends to
support that hypothesis.
If it is inter-thread timing, the main action for tracking down the
cause and fixing it should be a careful design review of the
synchronization strategy for the program. What is the plan for
preventing harmful simultaneous access to a single data structure by
multiple threads? Is it a good solid plan? If so, what went wrong with
implementing it? If not, the plan needs to be fixed and the code
modified to match the new plan.
That may lead to additional synchronization, or to moving operations to
the event handling thread. If so, remember to keep track of you deadlock
avoidance strategy as well.
Just fixing the cases that have shown up in your tests, without
examining the whole program, is a recipe for future trouble. There may
be another case lurking, only to show up at some inopportune time.
You may be able to make problems happen more frequently, and so improve
testing, by scattering sleep calls at critical places in a test version
of the program, such as inside loops that use iterators.
Patricia