7

Here is my code:

// eventList is a LinkedList

public void run() {

    Iterator<Event> it = eventList.iterator();
    int size = eventList.size();

    while(size > 0) {
        while(it.hasNext()) {
            Event e = it.next(); //flaged line

            if(e.ready()) {
                System.out.println(e);
                e.action();
                eventList.remove(e);
                --size;
            }
        }
    }
}

The error java.util.ConcurrentModificationException is thrown at the flag lined (Event e = it.next();). Do you see a mistake in my code that makes obvious the reason of that exception to be thrown?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
artaxerxe
  • 6,281
  • 21
  • 68
  • 106
  • possible duplicate of [loop on list with remove](http://stackoverflow.com/questions/1921104/loop-on-list-with-remove) – McDowell May 09 '11 at 12:09

2 Answers2

17

Your are modifying eventList while using eventList.remove() while iterating over it. You must not do this, or the Iterator becomes unusable.

Simply replace eventList.remove(e) with it.remove() and it should be fine.

Also, you can easily run into an endless loop if one of your events isn't ready in the first run because it.hasNext() will never return true once it returned false, but size won't be modified either. One solution would be to move the whole Iterator it = ... line inside the first while loop.

I'd also modify the outer while loop to use while (!e.isEmpty()) instead of trying to track the size of eventList manually.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • +1 for this answer; just a note, this problem is described in the docs for that exception: http://download.oracle.com/javase/6/docs/api/java/util/ConcurrentModificationException.html – Riccardo Cossu Apr 13 '11 at 07:35
  • Thank you. I think that the problem was that I looked to much time at code:) Thank you. – artaxerxe Apr 13 '11 at 07:37
1

You should remove the element through the iterator, otherwise the iterator gets reset because the underlying collection changed.

rsp
  • 23,135
  • 6
  • 55
  • 69