简体   繁体   English

Iterator.next()上的ConcurrentModificationException

[英]ConcurrentModificationException on Iterator.next()

I am getting a ConcurrentModificationException on the following code: 我在以下代码上收到ConcurrentModificationException:

private static List<Task> tasks = new LinkedList<Task>();
...
public void doTasks(){
    synchronized(tasks){
        Iterator<Task> it = tasks.iterator();

        while(it.hasNext()){
            Task t = it.next(); < Exception is always thrown on this line.

            if(t.isDone()){
                it.remove();
            } else {
                t.run();
            }
        }
    }
}
...
public void addTask(Task t){
    synchronized(tasks){
        tasks.add(t);
    }
}
...
public void clearTasks(){
    synchronized(tasks){
        tasks.clear();
    }
}

The Object "tasks" is not used anywhere else in the class. 对象“任务”不会在类中的任何其他位置使用。 I'm not sure why I'm getting the exception. 我不知道为什么我会得到例外。 Any help would be greatly appreciated. 任何帮助将不胜感激。

This is your issue: 这是你的问题:

if(t.isDone()){
    ...
} else {
    t.run(); // probably changing the task, so consequently the list tasks
}

EDIT: you can't change the tasks list in the loop. 编辑:您无法更改循环中的tasks列表。 Check out the ConcurrentModificationException documentation for more details. 查看ConcurrentModificationException文档以获取更多详细信息。

Cheers! 干杯!

Found the bug! 发现了这个bug! I forgot the scenario where the task ran in doTask() can actually call addTask(). 我忘记了在doTask()中运行任务的场景实际上可以调用addTask()。 However I am a bit confused why this can happen as I thought the "tasks" object would be locked by the doTask() function. 但是我有点困惑,为什么会发生这种情况,因为我认为“任务”对象会被doTask()函数锁定。

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

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