Skip to content
This repository was archived by the owner on Feb 26, 2023. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Serialized @background task cancellation bugfix
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:
#579 (comment)

Detected by ThreadActivityTest#cancellableSerializedBackgroundTasks()
(but not always due to the race condition)
  • Loading branch information
rom1v committed Jun 10, 2013
commit 8d0c9f52117309b59d40fbb8fde9a2d46dfbf711
Original file line number Diff line number Diff line change
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