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.
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. Check out the ConcurrentModificationException
documentation for more details.
Cheers!
Found the bug! I forgot the scenario where the task ran in doTask() can actually call addTask(). However I am a bit confused why this can happen as I thought the "tasks" object would be locked by the doTask() function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.