exception - Java application randomly errors with: java.util.ConcurrentModificationException -


this question has answer here:

so i'm trying create simple gravity using lwjgl, application randomly crashes java.util.concurrentmodificationexceptionexception. strange thing is not happen @ same time. crashes instantly other times runs fine 10 minutes before crashing.

main game class:

public static arraylist<block> blocks;  public game() {     blocks = new arraylist<block>();      for(int = 0; < 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 following:

exception in thread "main" java.util.concurrentmodificationexception     @ java.util.arraylist$itr.checkforcomodification(unknown source)     @ java.util.arraylist$itr.next(unknown source)     @ snakybo.gravitytest.block.block.update(block.java:26)     @ snakybo.gravitytest.game.update(game.java:34)     @ main.gameloop(main.java:52)     @ main.main(main.java:21) 

with (game.java:34) being line:

b.update(); 

and (block.java:26) being:

for(block b : game.blocks) 

if need full code, it's available on github

you multithreading. timertask runs on separate thread.

what happens this: spawnblock method being called on timer task thread modifies blocks list(adds 1 list). on main thread, update method called, in code iterates on blocks list.

because block added blocks list during iteration(during spawnblock method execution on other thread), concurrentmodificationexception.

replacing "for(block b : blocks)" "for(block b : new arraylist(blocks))" simple not performant solution: since iterate on new copy, can modify original list as want.

a better solution start making methods synchronized or rethink design, wrapping blocks list in synchronized wrapper.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -