So i'm trying to create simple gravity using LWJGL, but the application randomly crashes with the java.util.ConcurrentModificationException
exception. The strange thing is that is does not always happen at the same time. Sometimes it crashes instantly but other times it runs fine for 10 minutes before crashing.
Main game class:
public static ArrayList<Block> blocks;
public Game() {
blocks = new ArrayList<Block>();
for(int i = 0; i < 40; i++)
blocks.add(new BlockTest(i, 21, new float[] {0.4f, 0.6f, 0.7f}, false, 0));
spawnTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
spawnBlock();
}
}, 1000, 1000);
}
public void update() {
for(Block b : blocks)
b.update();
}
Block class:
/** Update block */
public void update() {
if(hasGravity) {
boolean colliding = false;
for(Block b : Game.blocks)
if(b.getBlockID() == 0) {
if(Util.checkBlockCollision(this, b)) {
colliding = true;
setBlockID(0);
}
}
if(fallDelay.over() && !colliding) {
setBlockYPosWithoutBlockSize(y += 2);
fallDelay.start();
}
}
}
The stack trace is the following:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at snakybo.gravitytest.block.Block.update(Block.java:26)
at snakybo.gravitytest.Game.update(Game.java:34)
at Main.gameLoop(Main.java:52)
at Main.main(Main.java:21)
With (Game.java:34) being this line:
b.update();
And (Block.java:26) being:
for(Block b : Game.blocks)
If you need the full code, it's available on Github