Question

I am getting an ConcurrentmodificationException while iterating over an object that is stored in the Cache.

The Controllercode looks like this:

....
SomeObj o = (SomeObj)Cache.get("obj");
for(listObj lo : o.getGetListObjects()){
    if(lo.getName().equals(name)){
        o.getEventRecipes().remove(lo);         
    }

The Execution is getting thrown as soon as the foreach-loop starts. There are no other threads that are explicitly running at the same time.

I am using Playframework 2.1.1 with Java.

Does anyone have an idea how to resolve this?

Was it helpful?

Solution

This means that the list of objects is being changed during the iteration. This can happen if

  1. other thread modify this collection while you are iterating
  2. you do it yourself by calling o.getGetListObjects().remove(lo) or o.getGetListObjects().add(otherObject) into your loop.

Second problem is easy to fix. Just do not modify collection during iteration or use Iterator.remove() for this purpose.

Second problem is harder. You should care not to use the same collection in different threads or use collection safe for such operation, e.g. ConcurrentSkipListSet.

You are welcome to provide more details about your application to get better recommendations.

OTHER TIPS

As AlexR said, using an iterator with iterator.remove() solved the problem.

Here is the code:

Iterator<SomeObj> i = e.getSomeObjs.iterator(); 
while(i.hasNext()){
    SomeObj o = i.next();
    if(o.getName().equals(name)){
        i.remove();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top