One really weird ConcurrentModificationException

Discussion in 'Plugin Development' started by Technius, May 6, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    Technius

    Ok, so my plugin loads some player data when they join, and then saves and removes it when they leave. The data is stored in an ArrayList. For some reason, it throws a CME. This is the event:

    Code:java
    1. @EventHandler(priority = EventPriority.MONITOR)
    2. public void playerLeave(PlayerQuitEvent event)
    3. {
    4. plugin.getDataManager().saveData(event.getPlayer());
    5. plugin.getQuestManager().removeData(event.getPlayer());
    6. }

    saveData writes the data to a file using java.io classes.
    removeData removes the data from the ArrayList.

    I even tried synchronized blocks on the removeData, but to no avail.

    Bump. It impedes the development of my great questing plugin.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 25, 2016
  2. Offline

    CorrieKay

    ill go ahead and take a guess that the CME is coming from within line 5. Whats the method look like?
     
  3. Offline

    phrstbrn

    Don't remove data while iterating over it unless you're using an iterator. My guess is you have something like this...

    Code:
    List list = ...;
     
    for (Object obj : list) {
      if (something) {
        list.remove(obj);
      }
    }
    
    Instead do this

    Code:
    List list = ...;
     
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
      Object obj = iter.next();
      if (something) {
        iter.remove();
      }
    }
    
    If you're using a Map, use entrySet(), values(), or keySet() and obtain an iterator from that.
     
  4. Offline

    Technius

    phrstbrn
    It roughly looks like this:
    Code:java
    1. for(Object o: list)
    2. {
    3. if(o.someMethod() == someObject)list.remove(o);
    4. }


    I'll try your iterator method later.

    phrstbrn
    Ah, it works. Thanks!

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 25, 2016
Thread Status:
Not open for further replies.

Share This Page