The code I am working on is throwing the aforementioned exception. I am not very experienced with multi-threaded programming and I'm not having a lot of luck troubleshooting this.
The program is written in Java using Processing and OSC. The main OSC event handler is adding elements to a Vector. It is triggered on user input and therefore highly unpredictable. This Vector is also being iterated over and updated in Processing's animation thread which happens very regularly at about 60 times per second.
Occasionally, the OSC events handler is called as the Vector is being iterated over in the animation thread and the exception is thrown.
I have tried adding the "synchronized
" modifier to the OSC event handler. I have also attempted to cue changes to the Vector until the next frame ( time step ) of the animation thread, but I'm finding that it just ends up delaying the exception being thrown.
What can I do to prevent this behavior? Is there a way to only access to the Vector if it isn't already in use?
Update: Two answers have suggested that the list is having elements added or removed as it is being iterated over. This is in fact what is happening due to the fact that OSC is triggering the handler from a thread other than the thread that is iterating over the list. I am looking for a way to prevent this.
Here is some pseudo-code:
Vector<String> list = new Vector<String>();
Vector<Particle> completedParticles = new Vector<Particle>();
public void oscEvent( OSCMessage message )
{
list.add( new Particle( message.x, message.y ) );
}
public void draw()
{
completedParticles.clear();
for( Particle p : list )
{
p.draw();
if( p.isComplete ) {
completedParticles.add( p );
}
}
list.removeAll( completedParticles );
}