Skip to content

Commit

Permalink
Serialized @background task cancellation bugfix
Browse files Browse the repository at this point in the history
If a serialized @background task was cancelled after it had been
submitted to the executor but before its run() method was called, then
the following tasks with the same serial identifier were not executed.

Issue reported here:
androidannotations#579 (comment)

Detected by ThreadActivityTest#cancellableSerializedBackgroundTasks()
(but not always due to the race condition)
  • Loading branch information
rom1v committed Jun 10, 2013
1 parent 77cbcea commit 8d0c9f5
Showing 1 changed file with 31 additions and 1 deletion.
Expand Up @@ -23,6 +23,7 @@
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import android.util.Log;

Expand Down Expand Up @@ -197,11 +198,21 @@ public static synchronized void cancelAll(String id, boolean mayInterruptIfRunni
for (int i = tasks.size() - 1; i >= 0; i--) {
Task task = tasks.get(i);
if (id.equals(task.id)) {
tasks.remove(i);
if (task.future != null) {
task.future.cancel(mayInterruptIfRunning);
if (!task.managed.getAndSet(true)) {
/*
* the task has been submitted to the executor, but its
* execution has not started yet, so that its run()
* method will never call postExecute()
*/
task.postExecute();
}
} else if (task.executionAsked) {
Log.w(TAG, "A task with id " + task.id + " cannot be cancelled (the executor set does not support it)");
} else {
/* this task has not been submitted to the executor */
tasks.remove(i);
}
}
}
Expand Down Expand Up @@ -252,6 +263,20 @@ public static abstract class Task implements Runnable {
private boolean executionAsked;
private Future<?> future;

/*
* A task can be cancelled after it has been submitted to the executor
* but before its run() method is called. In that case, run() will never
* be called, hence neither will postExecute(): the tasks with the same
* serial identifier (if any) will never be submitted.
*
* Therefore, cancelAll() *must* call postExecute() if run() is not
* started.
*
* This flag guarantees that either cancelAll() or run() manages this
* task post execution, but not both.
*/
private AtomicBoolean managed = new AtomicBoolean();

public Task(String id, int delay, String serial) {
if (!"".equals(id)) {
this.id = id;
Expand All @@ -267,6 +292,11 @@ public Task(String id, int delay, String serial) {

@Override
public void run() {
if (managed.getAndSet(true)) {
/* cancelled and postExecute() already called */
return;
}

try {
execute();
} finally {
Expand Down

0 comments on commit 8d0c9f5

Please sign in to comment.