In my current project, the game entities can be affected by the main game loop, the AWT thread, and later on, network packets or Lua scripts. To make things simple, I want to make a task queue to ensure that all of the actual changes happen in the main thread. This seems like it should work:
private static final Vector<Runnable> tasks = new Vector<Runnable>(Settings.MAX_TASKS);
public static void addTask(Runnable r)
{
synchronized(tasks)
{
tasks.add(r);
}
}
private static void processTasks()
{
synchronized(tasks)
{
Iterator<Runnable> itr = tasks.iterator();
while(itr.hasNext())
{
itr.next().run();
itr.remove();
}
}
}
It usually works OK, but if I get unlucky I get a ConcurrentModificationException in the processTasks() method when changing something using the GUI. Am I doing the synchronization wrong?