1

I am getting a ConcurrentModificationException on the following code:

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.

4

2 回答 2

3

这是你的问题:

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

编辑:您不能更改tasks循环中的列表。查看ConcurrentModificationException文档以获取更多详细信息。

干杯!

于 2013-04-26T21:39:15.873 回答
1

发现错误!我忘记了在doTask()中运行的任务实际上可以调用addTask()的场景。但是我有点困惑为什么会发生这种情况,因为我认为“任务”对象会被 doTask() 函数锁定。

于 2013-04-26T21:55:34.567 回答