From 7498ccb6b9a1e61281d998fc81adc9a4a5e87e56 Mon Sep 17 00:00:00 2001 From: Romain Guy Date: Fri, 16 Sep 2011 23:24:54 -0700 Subject: [PATCH] Check whether an AsyncTask is created/executed on a looper thread. Change-Id: I181b253c50a6579f35e61cd4b0c500379462e035 --- core/java/android/os/AsyncTask.java | 89 ++++++++++++++++++++--------- 1 file changed, 61 insertions(+), 28 deletions(-) diff --git a/core/java/android/os/AsyncTask.java b/core/java/android/os/AsyncTask.java index 9dea4c43b6993..1990935ff0611 100644 --- a/core/java/android/os/AsyncTask.java +++ b/core/java/android/os/AsyncTask.java @@ -32,12 +32,13 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** - *

AsyncTask enables proper and easy use of the UI thread. This class allows to - * perform background operations and publish results on the UI thread without - * having to manipulate threads and/or handlers.

+ *

AsyncTask enables proper and easy use of the UI thread (also called main thread) or + * any other looper thread. AsyncTask is most commonly used to interact with the UI thread. + * This class allows to perform background operations and publish results on a looper + * thread without having to manipulate threads and/or handlers.

* *

An asynchronous task is defined by a computation that runs on a background thread and - * whose result is published on the UI thread. An asynchronous task is defined by 3 generic + * whose result is published on a looper thread. An asynchronous task is defined by 3 generic * types, called Params, Progress and Result, * and 4 steps, called onPreExecute, doInBackground, * onProgressUpdate and onPostExecute.

@@ -101,7 +102,7 @@ import java.util.concurrent.atomic.AtomicInteger; *

The 4 steps

*

When an asynchronous task is executed, the task goes through 4 steps:

*
    - *
  1. {@link #onPreExecute()}, invoked on the UI thread immediately after the task + *
  2. {@link #onPreExecute()}, invoked on the looper thread immediately after the task * is executed. This step is normally used to setup the task, for instance by * showing a progress bar in the user interface.
  3. *
  4. {@link #doInBackground}, invoked on the background thread @@ -110,14 +111,14 @@ import java.util.concurrent.atomic.AtomicInteger; * of the asynchronous task are passed to this step. The result of the computation must * be returned by this step and will be passed back to the last step. This step * can also use {@link #publishProgress} to publish one or more units - * of progress. These values are published on the UI thread, in the + * of progress. These values are published on the looper thread, in the * {@link #onProgressUpdate} step.
  5. - *
  6. {@link #onProgressUpdate}, invoked on the UI thread after a + *
  7. {@link #onProgressUpdate}, invoked on the looper thread after a * call to {@link #publishProgress}. The timing of the execution is * undefined. This method is used to display any form of progress in the user * interface while the background computation is still executing. For instance, * it can be used to animate a progress bar or show logs in a text field.
  8. - *
  9. {@link #onPostExecute}, invoked on the UI thread after the background + *
  10. {@link #onPostExecute}, invoked on the looper thread after the background * computation finishes. The result of the background computation is passed to * this step as a parameter.
  11. *
@@ -135,8 +136,8 @@ import java.util.concurrent.atomic.AtomicInteger; *

There are a few threading rules that must be followed for this class to * work properly:

* + * + * @see Looper + * @see Handler */ public abstract class AsyncTask { private static final String LOG_TAG = "AsyncTask"; @@ -187,7 +191,13 @@ public abstract class AsyncTask { private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; - private static final InternalHandler sHandler = new InternalHandler(); + private static final ThreadLocal sHandler = + new ThreadLocal() { + @Override + protected InternalHandler initialValue() { + return new InternalHandler(); + } + }; private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; private final WorkerRunnable mWorker; @@ -196,6 +206,7 @@ public abstract class AsyncTask { private volatile Status mStatus = Status.PENDING; private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); + private final InternalHandler mHandler; private static class SerialExecutor implements Executor { final ArrayDeque mTasks = new ArrayDeque(); @@ -242,9 +253,8 @@ public abstract class AsyncTask { FINISHED, } - /** @hide Used to force static handler to be created. */ + /** @hide */ public static void init() { - sHandler.getLooper(); } /** @hide */ @@ -253,9 +263,20 @@ public abstract class AsyncTask { } /** - * Creates a new asynchronous task. This constructor must be invoked on the UI thread. + * Creates a new asynchronous task. This constructor must be invoked on the looper thread. + * + * @throws IllegalStateException if this constructor is invoked on a non-looper thread + * + * @see Looper */ public AsyncTask() { + if (Looper.myLooper() == null) { + throw new IllegalStateException("AsyncTask can be only instanciated on a " + + "looper thread. The current thread is " + Thread.currentThread()); + } + + mHandler = sHandler.get(); + mWorker = new WorkerRunnable() { public Result call() throws Exception { mTaskInvoked.set(true); @@ -295,7 +316,12 @@ public abstract class AsyncTask { } private Result postResult(Result result) { +<<<<<<< HEAD Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, +======= + @SuppressWarnings({"unchecked"}) + Message message = mHandler.obtainMessage(MESSAGE_POST_RESULT, +>>>>>>> 6c0d0b8... Check whether an AsyncTask is created/executed on a looper thread. new AsyncTaskResult(this, result)); message.sendToTarget(); return result; @@ -316,7 +342,7 @@ public abstract class AsyncTask { * by the caller of this task. * * This method can call {@link #publishProgress} to publish updates - * on the UI thread. + * on the looper thread. * * @param params The parameters of the task. * @@ -329,7 +355,7 @@ public abstract class AsyncTask { protected abstract Result doInBackground(Params... params); /** - * Runs on the UI thread before {@link #doInBackground}. + * Runs on the looper thread before {@link #doInBackground}. * * @see #onPostExecute * @see #doInBackground @@ -338,7 +364,7 @@ public abstract class AsyncTask { } /** - *

Runs on the UI thread after {@link #doInBackground}. The + *

Runs on the looper thread after {@link #doInBackground}. The * specified result is the value returned by {@link #doInBackground}.

* *

This method won't be invoked if the task was cancelled.

@@ -354,7 +380,7 @@ public abstract class AsyncTask { } /** - * Runs on the UI thread after {@link #publishProgress} is invoked. + * Runs on the looper thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values The values indicating progress. @@ -367,7 +393,7 @@ public abstract class AsyncTask { } /** - *

Runs on the UI thread after {@link #cancel(boolean)} is invoked and + *

Runs on the looper thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.

* *

The default implementation simply invokes {@link #onCancelled()} and @@ -390,7 +416,7 @@ public abstract class AsyncTask { * This method is invoked by the default implementation of * {@link #onCancelled(Object)}.

* - *

Runs on the UI thread after {@link #cancel(boolean)} is invoked and + *

Runs on the looper thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.

* * @see #onCancelled(Object) @@ -425,7 +451,7 @@ public abstract class AsyncTask { * an attempt to stop the task.

* *

Calling this method will result in {@link #onCancelled(Object)} being - * invoked on the UI thread after {@link #doInBackground(Object[])} + * invoked on the looper thread after {@link #doInBackground(Object[])} * returns. Calling this method guarantees that {@link #onPostExecute(Object)} * is never invoked. After invoking this method, you should check the * value returned by {@link #isCancelled()} periodically from @@ -498,14 +524,15 @@ public abstract class AsyncTask { * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings on * its use. * - *

This method must be invoked on the UI thread. + *

This method must be invoked on the looper thread. * * @param params The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException If {@link #getStatus()} returns either - * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. + * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED} or + * the current thread is not a looper thread. */ public final AsyncTask execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); @@ -531,7 +558,7 @@ public abstract class AsyncTask { * executed in serial; to guarantee such work is serialized regardless of * platform version you can use this function with {@link #SERIAL_EXECUTOR}. * - *

This method must be invoked on the UI thread. + *

This method must be invoked on the looper thread. * * @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a * convenient process-wide thread pool for tasks that are loosely coupled. @@ -540,10 +567,16 @@ public abstract class AsyncTask { * @return This instance of AsyncTask. * * @throws IllegalStateException If {@link #getStatus()} returns either - * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. + * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED} or + * the current thread is not a looper thread. */ public final AsyncTask executeOnExecutor(Executor exec, Params... params) { + if (Looper.myLooper() == null) { + throw new IllegalStateException("AsyncTask can be only instanciated on a " + + "looper thread. The current thread is " + Thread.currentThread()); + } + if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: @@ -576,9 +609,9 @@ public abstract class AsyncTask { /** * This method can be invoked from {@link #doInBackground} to - * publish updates on the UI thread while the background computation is + * publish updates on the looper thread while the background computation is * still running. Each call to this method will trigger the execution of - * {@link #onProgressUpdate} on the UI thread. + * {@link #onProgressUpdate} on the looper thread. * * {@link #onProgressUpdate} will note be called if the task has been * canceled. @@ -590,7 +623,7 @@ public abstract class AsyncTask { */ protected final void publishProgress(Progress... values) { if (!isCancelled()) { - sHandler.obtainMessage(MESSAGE_POST_PROGRESS, + mHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult(this, values)).sendToTarget(); } }