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?
Your are modifying
eventListwhile usingeventList.remove()while iterating over it. You must not do this, or theIteratorbecomes unusable.Simply replace
eventList.remove(e)withit.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 returntrueonce it returnedfalse, butsizewon’t be modified either. One solution would be to move the wholeIterator it = ...line inside the firstwhileloop.I’d also modify the outer
whileloop to usewhile (!e.isEmpty())instead of trying to track the size ofeventListmanually.