简体   繁体   中英

Getting Concurrent Modification Exception while not removing anything

Im writing simple Tower Defence game in Java. Here is method which finds path from spawn (set in constructor) to nearest base.

public int[] findPath(Field startField) {
    ArrayList<TestMonster> monsrs = new ArrayList<TestMonster>();
    TestMonster first = new TestMonster(startField.getCenter(), getStartingDirection(startField), new int[0]);
    monsters.add(first);
    while (true) {
        for (TestMonster monsr : monsrs) {
            monster.move();
            if (getFieldFromCenter(monsr.getPoint()).getState() == 101)
                return monsr.getPath();
            Field field = getFieldFromCenter(monsr.getPoint());
            if (field.isUp())
                monsters.add(new TestMonster(monsr.getPoint(), 0, monster.getPath()));
            if (field.isRight())
                monsters.add(new TestMonster(monsr.getPoint(), 90, monster.getPath()));
            if (field.isDown())
                monsters.add(new TestMonster(monsr.getPoint(), 180, monster.getPath()));
            if (field.isLeft())
                monsters.add(new TestMonster(monsr.getPoint(), 270, monster.getPath()));
            if (monsrs.isEmpty())
                return null;
        }
    }
}

It may return array of next directions in which monster moved to get to base or null if there is no path. It goes through fields which are Field class objects. On every field monster searches for possible moves and for every creates new monster with set direction. New monster inherits also moves array to add to it its own direction and then give it to new monster and so on. And my question is where in my code is possibility of concurrent mod ex? And how can I prevent it?

STACK TRACE:

Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at towerdefence.MainPanel.findPath(MainPanel.java:160)
at towerdefence.MainPanel$1.actionPerformed(MainPanel.java:62)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1664)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2879)
at javax.swing.KeyboardManager.fireBinding(KeyboardManager.java:306)
at javax.swing.KeyboardManager.fireKeyboardAction(KeyboardManager.java:250)
at javax.swing.JComponent.processKeyBindingsForAllComponents(JComponent.java:2971)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2963)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2842)
at java.awt.Component.processEvent(Component.java:6282)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)

Iterators are fail fast, so cannot concurrently modify the collection if you are using an iterator over it to iterate the collection. means using an iterator, you cannot iterate and modify the collection at the same time. like adding or removing something to the collections over which you are itearting.

What is a fail fast iterator

Also see this question fail-fast iterator

Try this, may solve your problem

List<TestMonster> monsrs = Collections.synchronizedList(new ArrayList<TestMonster>());

ArrayList implementation is not synchronized, You'll need to synchronize the access to your list. You can accomplish this either by synchronizing the encpasulating object or by using Collections.synchronizedList method.

Please check this for more information

Inside the loop, consider adding your objects to a temporary list and afterwards (outside the loop) add to your original list.

You can't modify the list you are iterating on. Example:

List<Object> list = new ArrayList<Object>();
list.add("object 1");
list.add("object 2");
for (Object object : list) {
    list.add("another one");
}

It will throw a java.util.ConcurrentModificationException as well.

For a more detailed information, please read the documentation: http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM