0

So this is a function from my snake game code. Basically I was initially doing a for to go though the LinkedList<Point> that is the snake but since it was throwing the exception I thought changing it using iterators would help. Apparently not. How can I fix this?

public void drawSnake(Graphics g) {
    g.setColor(Color.green);
    Iterator<Point> iterator = snake.iterator();
    while(iterator.hasNext()){
        Point p =iterator.next();
        g.fillRect(p.x * BOX_WIDTH, p.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
    }
    g.setColor(Color.black);
}
Alexey Malev
  • 6,408
  • 4
  • 34
  • 52
Luís Gonçalves
  • 338
  • 5
  • 17
  • 2
    Are you sure this is the code throwing the exception? Doesn't seem likely at all to me. – kviiri May 17 '14 at 09:08
  • 2
    Agree with @kviiri , there's no modification in this example, so this should not throw any Exception. – Dmitry Ginzburg May 17 '14 at 09:12
  • 1
    this may help you http://stackoverflow.com/questions/8189466/java-util-concurrentmodificationexception – Vikas Singh May 17 '14 at 09:20
  • @kviiri I do udnerstand what you are saying since there are no (at least visible) modifications to the snake in that function but the error points towards it :/ – Luís Gonçalves May 17 '14 at 09:53
  • 1
    @Asura14, post the stack trace of the exception, it might have something of interest. – kviiri May 17 '14 at 10:27
  • @kviiri actually I found the problem is solved. I'll answer my own question as soon as StackOverflow allows me to. Thank you for the help anyway – Luís Gonçalves May 17 '14 at 12:39

1 Answers1

2

In general, this exception occurs when collection has been modified while iterating over it. Most likely that means that snake is being modified in another thread. This code, considered independently, should not throw CME, so this is the only possible explanation remaining.

Try looking for all usages of snake variable and analyze whether they can be done together with the code you posted.

Another very, very unlike possibility is that g.fillRect() method deletes p from the snake collection. This can possible if you overrided the method, for example.

Alexey Malev
  • 6,408
  • 4
  • 34
  • 52