Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentModificationException even with using Collections.sychronizedMap on a LinkedHashMap [duplicate]

I'm using a Map object in my class that I've synchronized with Collections.synchronizedMap() for a LinkedHashMap like so:

private GameObjectManager(){
        gameObjects = Collections.synchronizedMap(new LinkedHashMap<String, GameObject>());
}

I'm getting a concurrent modification exception on the third line of this function:

public static void frameElapsed(float msElapsed){
    if(!INSTANCE.gameObjects.isEmpty()){
        synchronized(INSTANCE.gameObjects){
            for(GameObject object : INSTANCE.gameObjects.values()){...}
        }
    }
}

All other locations where I am iterating through the Map, I am synchronizing on the map per the docs.

There are other functions in my class that use this Map (the synchronized one!) and they put() and remove() objects, but this shouldn't matter though. What am I doing wrong? Please ask for more code, not sure what else to put.

Oh, and the log message:

08-20 15:55:30.109: E/AndroidRuntime(14482): FATAL EXCEPTION: GLThread 1748
08-20 15:55:30.109: E/AndroidRuntime(14482): java.util.ConcurrentModificationException
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     java.util.LinkedHashMap$LinkedHashIterator.nextEntry(LinkedHashMap.java:350)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     java.util.LinkedHashMap$ValueIterator.next(LinkedHashMap.java:374)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     package.GameObjectManager.frameElapsed(GameObjectManager.java:247)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     package.GamekitInterface.render(Native Method)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     package.GamekitInterface.renderFrame(GamekitInterface.java:332)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     com.qualcomm.QCARSamples.ImageTargets.GameEngineInterface.onDrawFrame(GameEngineInterface.java:107)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1516)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
like image 550
mpellegr Avatar asked Aug 20 '13 19:08

mpellegr


People also ask

How can you avoid ConcurrentModificationException while iterating a collection?

To Avoid ConcurrentModificationException in single-threaded environment. You can use the iterator remove() function to remove the object from underlying collection object. But in this case, you can remove the same object and not any other object from the list.

How do I fix ConcurrentModificationException in Java?

How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.

What is ConcurrentModificationException what will happen if we use remove?

The ConcurrentModificationException occurs when an object is tried to be modified concurrently when it is not permissible. This exception usually comes when one is working with Java Collection classes. For Example - It is not permissible for a thread to modify a Collection when some other thread is iterating over it.

What is ConcurrentModificationException and how it can be prevented?

ConcurrentModificationException is a predefined Exception in Java, which occurs while we are using Java Collections, i.e whenever we try to modify an object concurrently without permission ConcurrentModificationException occurs which is present in java. util package.


3 Answers

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 call remove() 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).
like image 170
yshavit Avatar answered Sep 20 '22 01:09

yshavit


you are using for-each alike version of for loop. In Java it is forbidden to add or remove elements from iterated collection in such loop. To avoid this situation, use collections iterator. From iterator, you can remove elements.

like image 42
Antoniossss Avatar answered Sep 21 '22 01:09

Antoniossss


Collections.synchronizedMap() doesn't help you when iterating. That will just make your map perform the put/get/remove operations atomically (that means you won't have two such operations running simultaneously).

When iterating, you fetch each element and do something with it. But what if the very element that you are acting upon within your iteration as your current element gets removed by some other thread ?

This is what the exception is trying to prevent, as you may get a result that doesn't correspond to any actual snapshot of your map: if you're computing the sum of your Integer values, for example, the elements you already added may get removed and others may be added while you iterate, so you'll end up with a sum that doesn't match any "snapshot" of your map.

For what you're trying to do, the only solution would be to perform the whole iteration within some synchronized block but it's mandatory that you synchronize on the same monitor used by your map operations. And the Collections.syncrhonizedMap() provides a wrapper which synchronizes on some internal mutex, not on the this reference. Therefore, your attempt to prevent any modification to your map while iterating will fail.

like image 43
Costi Ciudatu Avatar answered Sep 21 '22 01:09

Costi Ciudatu