[英]ConcurrentModificationException in Playframework
我在遍歷存儲在Cache中的對象時收到ConcurrentmodificationException 。
Controllercode看起來像這樣:
....
SomeObj o = (SomeObj)Cache.get("obj");
for(listObj lo : o.getGetListObjects()){
if(lo.getName().equals(name)){
o.getEventRecipes().remove(lo);
}
一旦foreach循環開始,執行就會被拋出。 沒有其他線程在同一時間顯式運行。
我正在Java中使用Playframework 2.1.1 。
有誰知道如何解決這個問題?
這意味着在迭代過程中將更改對象列表。 如果發生這種情況
o.getGetListObjects().remove(lo)
調用o.getGetListObjects().remove(lo)
或o.getGetListObjects().add(otherObject)
來自己完成操作。 第二個問題很容易解決。 只是不要在迭代過程中修改集合,或者為此目的使用Iterator.remove()
。
第二個問題更難。 您應該注意不要在不同的線程中使用相同的集合,也不要對此類操作使用安全的集合,例如ConcurrentSkipListSet
。
歡迎您提供有關您的應用程序的更多詳細信息,以獲得更好的建議。
正如AlexR所說,在iterator.remove()中使用迭代器可以解決此問題。
這是代碼:
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.