2011-08-12 02:28:47 [SEVERE] java.util.ConcurrentModificationException

Discussion in 'Plugin Development' started by skeletonofchaos, Aug 11, 2011.

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

    skeletonofchaos

    Anyone have any idea what this means 2011-08-12 02:28:47 [SEVERE] java.util.ConcurrentModificationException?
     
  2. Offline

    bassfader

  3. Offline

    bergerkiller

    To simplify it a bit more. This error occurs when you try to remove elements from a collection you are currently looping in. For example, this causes the error:
    Code:
    ArrayList<String> items = new ArrayList<String>();
    items.add("test");
    items.add("bukkit");
    items.add("add");
    items.add("remove");
    items.add("post");
    for (String item : items) {
        if (item.equalsIgnoreCase("remove")) {
            items.remove(item);
        }
    }
    Why? Because you removed an item in the 'items' array you currently loop in. The underlying java code can't perform a 'next' because the collection has changed. Two ways to fix this:


    - Clone the array/list and loop through that:
    Code:
    for (String item : items.toArray(new String[0])) {
        items.remove(item);
    }
    - Store the items to remove in a temporary list and loop through that list afterwards
    Code:
    ArrayList<String> removelist = new ArrayList<String>();
    for (String item : items) {
        removelist.add(item);
    }
    for (String item : removelist) {
        items.remove(item);
    }
    There are more ways. The same can happen if you would change a variable in a separate ASync thread.
     
Thread Status:
Not open for further replies.

Share This Page