Reputation: 9599
I've got the following code:
public static void pauseAllTimers() {
for(Timer timer : Timer.allTimers) {
timer.pause();
}
}
Where Timer
instances are being added and removed to allTimers
within one thread (as far as I can tell, unless I'm overseeing something in my code).
Why is my code yielding a Concurrent Modification Exception?
Upvotes: 0
Views: 72
Reputation: 1503799
You're iterating over the collection while you're removing from it - assuming that pause()
removes the timer. Don't do that - you're modifying a collection while you're still iterating over it, which is a concurrent modification even though there's only one thread.
Copy the set of timers to a list, and then iterate over that:
List<Timer> timers = new ArrayList<Timer>(Timer.allTimers);
for (Timer timer : timers) {
timer.pause();
}
Upvotes: 3