Stuck with "java.util.ConcurrentModificationException"
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 on the aligned flag ( Event e = it.next();
). Do you see an error in my code that makes the reason for throwing this exception obvious?
You change eventList
when using eventList.remove()
, iterating over it. You must not do this, or the Iterator
becomes unusable.
Just replace eventList.remove(e)
with it.remove()
and everything should be fine.
In addition, you can easily start an infinite loop if one of your events fails on the first run, because it.hasNext()
will never return true
after it returns false
, but size
can also not be changed. One solution would be to move the entire line of Iterator it = ...
inside the first while
.
I would also modify the outer while
to use while (!e.isEmpty())
instead of manually tracking the size of the eventList
.