简体   繁体   English

Playframework中的ConcurrentModificationException

[英]ConcurrentModificationException in Playframework

I am getting an ConcurrentmodificationException while iterating over an object that is stored in the Cache. 我在遍历存储在Cache中的对象时收到ConcurrentmodificationException

The Controllercode looks like this: Controllercode看起来像这样:

....
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. 一旦foreach循环开始,执行就会被抛出。 There are no other threads that are explicitly running at the same time. 没有其他线程在同一时间显式运行。

I am using Playframework 2.1.1 with Java . 我正在Java中使用Playframework 2.1.1

Does anyone have an idea how to resolve this? 有谁知道如何解决这个问题?

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. 您可以通过在o.getGetListObjects().remove(lo)调用o.getGetListObjects().remove(lo)o.getGetListObjects().add(otherObject)来自己完成操作。

Second problem is easy to fix. 第二个问题很容易解决。 Just do not modify collection during iteration or use Iterator.remove() for this purpose. 只是不要在迭代过程中修改集合,或者为此目的使用Iterator.remove()

Second problem is harder. 第二个问题更难。 You should care not to use the same collection in different threads or use collection safe for such operation, eg ConcurrentSkipListSet . 您应该注意不要在不同的线程中使用相同的集合,也不要对此类操作使用安全的集合,例如ConcurrentSkipListSet

You are welcome to provide more details about your application to get better recommendations. 欢迎您提供有关您的应用程序的更多详细信息,以获得更好的建议。

As AlexR said, using an iterator with iterator.remove() solved the problem. 正如AlexR所说,在iterator.remove()中使用迭代器可以解决此问题。

Here is the code: 这是代码:

Iterator<SomeObj> i = e.getSomeObjs.iterator(); 
while(i.hasNext()){
    SomeObj o = i.next();
    if(o.getName().equals(name)){
        i.remove();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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