How do I handle the java.util.ConcurrentModificationException exception?


There is a code: link to github. During execution, an exception is thrown Exception in thread "AWT-EventQueue-0" java. util.ConcurrentModificationException Image Knowledgeable people tell me how to overcome the problem. Thank you in advance)

Author: Abyx, 2015-09-28

3 answers

It doesn't need to be processed. This exception means that in your code you delete an element directly from the collection while using the iterator. Since in this case there is uncertainty where the iterator should continue and which subsequent elements should go through, an exception is thrown. To change the entity correctly, use the iterator methods, for example, iterator.remove().

 19
Author: etki, 2015-09-28 12:48:33

For example, you can set a lock before starting the ArrayList modification and release the lock after the modification is completed. Use the non-competitive ArrayList data structure. This data structure will work correctly if there is only one stream.

    while (i.hasNext()) {
        synchronized (i) {
            Enemy e = i.next();
            if (e.x >= 1600 || e.x <= -1600) {
                i.remove();
            } else {
                e.move(); // поправить позже
                g.drawImage(e.img, e.x, e.y, null);
            }
        }
    }

In this code, the lock is released after the modification is completed. You can rewrite the code like this:

    while (i.hasNext()) {
        boolean isDrawImage = false;
        synchronized (i) {
            Enemy e = i.next();
            if (e.x >= 1600 || e.x <= -1600) {
                i.remove();
            } else {
                e.move(); // поправить позже
                isDrawImage = true;
            }
        }
        if (isDrawImage)
           g.drawImage(e.img, e.x, e.y, null);
    }
 3
Author: , 2015-09-28 12:38:43

In addition to the answer to etki, I provide the code for correctly deleting a collection element inside the iterator loop:

Iterator<String> i = strings.iterator();
while (i.hasNext()) {
    String value = i.next(); // должен быть вызван перед тем, как вызывается i.remove()
    // какой-то код
    i.remove(); // Элемент value был удалён из коллекции strings
}
 0
Author: Alexey Timokhin, 2017-11-21 14:25:09