I’m trying to iterate over a list of objects. I get the ConcurrentModificationException error. However I am not changing/removing the objects. Also the method game.getRooms() is synchronized. What am I doing wrong?
Iterator<Room> it = game.getRooms().iterator();
while (it.hasNext()) {
Room room = it.next();
synchronized (room) {
Image tile;
if (room.getTile() == Tiles.WALL) {
tile = TileGraphics.wall;
} else if (room.getTile() == Tiles.EXIT) {
tile = TileGraphics.exit;
} else {
tile = TileGraphics.floor;
}
tile.setAlpha(room.getLight());
tile.draw(room.getX() * tile.getWidth(), room.getY() * tile.getHeight());
}
}
Stacktrace:
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at game.screens.GameScreen.render(GameScreen.java:62)
at org.newdawn.slick.state.StateBasedGame.render(StateBasedGame.java:199)
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:681)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:408)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:318)
at game.Main.main(Main.java:23)
Tue Jun 07 22:05:03 EEST 2011 ERROR:Game.render() failure – check the game code.
org.newdawn.slick.SlickException: Game.render() failure – check the game code.
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:684)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:408)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:318)
at game.Main.main(Main.java:23)
Line 62 is being Room room = it.next();
If this list is being used in a multithreaded application, any thread could
be accessing the list and modifying/iterating over the backing list with the iterator.
Is your list being created with a synchronised wrapper? (Collections.synchronizedList(new ArrayList()) for example).
Synchronising the declaration of the list is not enough, nor is just synchronizing the method call. Every place the list is iterated over needs a synchronized block, synchronized against the list.
Read http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedList(java.util.List)