0

Error log:

[26-12-13 3:16]: java.util.ConcurrentModificationException
[26-12-13 3:16]: at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
[26-12-13 3:16]: at java.util.ArrayList$Itr.next(ArrayList.java:791)
[26-12-13 3:16]: at server.event.cycle.CycleEventHandler.stopEvents(CycleEventHandler.java:60) [26-12-13 3:16]: at server.model.players.Client.logout(Client.java:292)

Method:

public void stopEvents(Object owner) {
    for (CycleEventContainer c : events) {
        if(c.getOwner() == owner) {
            c.stop();
        }
    }
}

Question: How do I fix this error?

Edit; stop method:

public void stop() {
    isRunning = false;
    event.stop();
}

Would this work?

public void stopEvents(Object owner) {
    ArrayList<CycleEventContainer> garbageEvents = new ArrayList<>();
    for (CycleEventContainer c : events) {
        if(c.getOwner() == owner) {
            garbageEvents.add(c);
        }
    }
    for (CycleEventContainer c: garbageEvents) {
        c.stop();
    }
    garbageEvents.clear();
}
user2997204
  • 1,344
  • 2
  • 12
  • 24
  • 2
    Is `events` being changed anywhere else that either happens within `c.stop()`, `c.getOwner()`, or in a different thread? – Sotirios Delimanolis Dec 26 '13 at 02:23
  • ... or being removed? – PM 77-1 Dec 26 '13 at 02:32
  • `ConcurrentModificationException` is thrown when the data structure below an iterator changes while the iterator iterates it. My guess is that `c.stop()` is doing something that changes `events` (such as, removing `c` from `events`) which causes this exception. – Nir Alfasi Dec 26 '13 at 02:33
  • Yes, which approach do I use then? – user2997204 Dec 26 '13 at 02:34
  • Typically you don't use a straight iterator OR you collect things to be removed in a list and do the removal as a batch after the iteration is complete. At least that's the approaches I've typically seen. – J Trana Dec 26 '13 at 02:38
  • @user2997204 Doing `garbageEvents.clear()` just clears out the new list and leaves the original list intact. You want to do `events.removeAll(garbageEvents)`. – Chris Hayes Dec 26 '13 at 02:45

2 Answers2

1

ConcurrentModificationException will be thrown every time a Collection adds or removes any element while iterating it. This is introduced to let the thread who iterates the Collection aware of the modification. So I believe your codes modify events somewhere else in other threads since your codes listed here don't seem to add or remove any element. You may check out this. Hope it helps.

LeoYoung
  • 26
  • 2
0

In this situation ConcurrentModificationException means that another thread is trying to modify events. You need to use synchronization or a thread-safe collection instead of ArrayList.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275