Despite the name, this has nothing to do with concurrency in the multithreading sense. You can't modify this map while iterating on it, except by invoking remove()
on the iterator. That is, where you have...
for(GameObject object : INSTANCE.gameObjects.values()){...}
if the ...
modifies INSTANCE.gameObjects.values()
(for instance, removing or adding an element), the next invocation to next()
on the iterator (which is implicit to the for
loop) will throw that exception.
This is true of most collections and Map implementations. The javadocs usually specify that behavior, though not always obviously.
Fixes:
If what you're trying to do is remove the element, you need to explicitly get the
Iterator<GameObject>
and callremove()
on it.for (Iterator<GameObject> iter = INSTANCE.getObjects().values(); iter.hasNext(); ;) { GameObject object = iter.next(); if (someCondition(object)) { iter.remove(); } }
- If you're trying to add an element, you need to create a temporary collection to hold the elements you want to add, and then after the iterator is finished,
putAll(temporaryMapForAdding)
.