ModernAsyncTask.java revision ea85d97d6a7eed3aedbde96bbeb40690599ef071
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.support.v4.content;
18
19import java.util.concurrent.BlockingQueue;
20import java.util.concurrent.Callable;
21import java.util.concurrent.CancellationException;
22import java.util.concurrent.ExecutionException;
23import java.util.concurrent.Executor;
24import java.util.concurrent.FutureTask;
25import java.util.concurrent.LinkedBlockingQueue;
26import java.util.concurrent.ThreadFactory;
27import java.util.concurrent.ThreadPoolExecutor;
28import java.util.concurrent.TimeUnit;
29import java.util.concurrent.TimeoutException;
30import java.util.concurrent.atomic.AtomicBoolean;
31import java.util.concurrent.atomic.AtomicInteger;
32
33import android.os.AsyncTask;
34import android.os.Handler;
35import android.os.Looper;
36import android.os.Message;
37import android.os.Process;
38
39/**
40 * Copy of the required parts of {@link android.os.AsyncTask} from Android 3.0 that is
41 * needed to support AsyncTaskLoader.  We use this rather than the one from the platform
42 * because we rely on some subtle behavior of AsyncTask that is not reliable on
43 * older platforms.
44 *
45 * <p>Note that for now this is not publicly available because it is not a
46 * complete implementation, only sufficient for the needs of
47 * {@link AsyncTaskLoader}.
48 */
49abstract class ModernAsyncTask<Params, Progress, Result> {
50    private static final String LOG_TAG = "AsyncTask";
51
52    private static final int CORE_POOL_SIZE = 5;
53    private static final int MAXIMUM_POOL_SIZE = 128;
54    private static final int KEEP_ALIVE = 1;
55
56    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
57        private final AtomicInteger mCount = new AtomicInteger(1);
58
59        public Thread newThread(Runnable r) {
60            return new Thread(r, "ModernAsyncTask #" + mCount.getAndIncrement());
61        }
62    };
63
64    private static final BlockingQueue<Runnable> sPoolWorkQueue =
65            new LinkedBlockingQueue<Runnable>(10);
66
67    /**
68     * An {@link Executor} that can be used to execute tasks in parallel.
69     */
70    public static final Executor THREAD_POOL_EXECUTOR
71            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
72                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
73
74    private static final int MESSAGE_POST_RESULT = 0x1;
75    private static final int MESSAGE_POST_PROGRESS = 0x2;
76
77    private static InternalHandler sHandler;
78
79    private static volatile Executor sDefaultExecutor = THREAD_POOL_EXECUTOR;
80    private final WorkerRunnable<Params, Result> mWorker;
81    private final FutureTask<Result> mFuture;
82
83    private volatile Status mStatus = Status.PENDING;
84
85    private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
86
87    /**
88     * Indicates the current status of the task. Each status will be set only once
89     * during the lifetime of a task.
90     */
91    public enum Status {
92        /**
93         * Indicates that the task has not been executed yet.
94         */
95        PENDING,
96        /**
97         * Indicates that the task is running.
98         */
99        RUNNING,
100        /**
101         * Indicates that {@link android.os.AsyncTask#onPostExecute(Object)} has finished.
102         */
103        FINISHED,
104    }
105
106    private static Handler getHandler() {
107        synchronized (AsyncTask.class) {
108            if (sHandler == null) {
109                sHandler = new InternalHandler();
110            }
111            return sHandler;
112        }
113    }
114
115    /** @hide */
116    public static void setDefaultExecutor(Executor exec) {
117        sDefaultExecutor = exec;
118    }
119
120    /**
121     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
122     */
123    public ModernAsyncTask() {
124        mWorker = new WorkerRunnable<Params, Result>() {
125            public Result call() throws Exception {
126                mTaskInvoked.set(true);
127
128                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
129                return postResult(doInBackground(mParams));
130            }
131        };
132
133        mFuture = new FutureTask<Result>(mWorker) {
134            @Override
135            protected void done() {
136                try {
137                    final Result result = get();
138
139                    postResultIfNotInvoked(result);
140                } catch (InterruptedException e) {
141                    android.util.Log.w(LOG_TAG, e);
142                } catch (ExecutionException e) {
143                    throw new RuntimeException(
144                            "An error occurred while executing doInBackground()", e.getCause());
145                } catch (CancellationException e) {
146                    postResultIfNotInvoked(null);
147                } catch (Throwable t) {
148                    throw new RuntimeException(
149                            "An error occurred while executing doInBackground()", t);
150                }
151            }
152        };
153    }
154
155    private void postResultIfNotInvoked(Result result) {
156        final boolean wasTaskInvoked = mTaskInvoked.get();
157        if (!wasTaskInvoked) {
158            postResult(result);
159        }
160    }
161
162    private Result postResult(Result result) {
163        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
164                new AsyncTaskResult<Result>(this, result));
165        message.sendToTarget();
166        return result;
167    }
168
169    /**
170     * Returns the current status of this task.
171     *
172     * @return The current status.
173     */
174    public final Status getStatus() {
175        return mStatus;
176    }
177
178    /**
179     * Override this method to perform a computation on a background thread. The
180     * specified parameters are the parameters passed to {@link #execute}
181     * by the caller of this task.
182     *
183     * This method can call {@link #publishProgress} to publish updates
184     * on the UI thread.
185     *
186     * @param params The parameters of the task.
187     *
188     * @return A result, defined by the subclass of this task.
189     *
190     * @see #onPreExecute()
191     * @see #onPostExecute
192     * @see #publishProgress
193     */
194    protected abstract Result doInBackground(Params... params);
195
196    /**
197     * Runs on the UI thread before {@link #doInBackground}.
198     *
199     * @see #onPostExecute
200     * @see #doInBackground
201     */
202    protected void onPreExecute() {
203    }
204
205    /**
206     * <p>Runs on the UI thread after {@link #doInBackground}. The
207     * specified result is the value returned by {@link #doInBackground}.</p>
208     *
209     * <p>This method won't be invoked if the task was cancelled.</p>
210     *
211     * @param result The result of the operation computed by {@link #doInBackground}.
212     *
213     * @see #onPreExecute
214     * @see #doInBackground
215     * @see #onCancelled(Object)
216     */
217    @SuppressWarnings({"UnusedDeclaration"})
218    protected void onPostExecute(Result result) {
219    }
220
221    /**
222     * Runs on the UI thread after {@link #publishProgress} is invoked.
223     * The specified values are the values passed to {@link #publishProgress}.
224     *
225     * @param values The values indicating progress.
226     *
227     * @see #publishProgress
228     * @see #doInBackground
229     */
230    @SuppressWarnings({"UnusedDeclaration"})
231    protected void onProgressUpdate(Progress... values) {
232    }
233
234    /**
235     * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
236     * {@link #doInBackground(Object[])} has finished.</p>
237     *
238     * <p>The default implementation simply invokes {@link #onCancelled()} and
239     * ignores the result. If you write your own implementation, do not call
240     * <code>super.onCancelled(result)</code>.</p>
241     *
242     * @param result The result, if any, computed in
243     *               {@link #doInBackground(Object[])}, can be null
244     *
245     * @see #cancel(boolean)
246     * @see #isCancelled()
247     */
248    @SuppressWarnings({"UnusedParameters"})
249    protected void onCancelled(Result result) {
250        onCancelled();
251    }
252
253    /**
254     * <p>Applications should preferably override {@link #onCancelled(Object)}.
255     * This method is invoked by the default implementation of
256     * {@link #onCancelled(Object)}.</p>
257     *
258     * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
259     * {@link #doInBackground(Object[])} has finished.</p>
260     *
261     * @see #onCancelled(Object)
262     * @see #cancel(boolean)
263     * @see #isCancelled()
264     */
265    protected void onCancelled() {
266    }
267
268    /**
269     * Returns <tt>true</tt> if this task was cancelled before it completed
270     * normally. If you are calling {@link #cancel(boolean)} on the task,
271     * the value returned by this method should be checked periodically from
272     * {@link #doInBackground(Object[])} to end the task as soon as possible.
273     *
274     * @return <tt>true</tt> if task was cancelled before it completed
275     *
276     * @see #cancel(boolean)
277     */
278    public final boolean isCancelled() {
279        return mFuture.isCancelled();
280    }
281
282    /**
283     * <p>Attempts to cancel execution of this task.  This attempt will
284     * fail if the task has already completed, already been cancelled,
285     * or could not be cancelled for some other reason. If successful,
286     * and this task has not started when <tt>cancel</tt> is called,
287     * this task should never run. If the task has already started,
288     * then the <tt>mayInterruptIfRunning</tt> parameter determines
289     * whether the thread executing this task should be interrupted in
290     * an attempt to stop the task.</p>
291     *
292     * <p>Calling this method will result in {@link #onCancelled(Object)} being
293     * invoked on the UI thread after {@link #doInBackground(Object[])}
294     * returns. Calling this method guarantees that {@link #onPostExecute(Object)}
295     * is never invoked. After invoking this method, you should check the
296     * value returned by {@link #isCancelled()} periodically from
297     * {@link #doInBackground(Object[])} to finish the task as early as
298     * possible.</p>
299     *
300     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
301     *        task should be interrupted; otherwise, in-progress tasks are allowed
302     *        to complete.
303     *
304     * @return <tt>false</tt> if the task could not be cancelled,
305     *         typically because it has already completed normally;
306     *         <tt>true</tt> otherwise
307     *
308     * @see #isCancelled()
309     * @see #onCancelled(Object)
310     */
311    public final boolean cancel(boolean mayInterruptIfRunning) {
312        return mFuture.cancel(mayInterruptIfRunning);
313    }
314
315    /**
316     * Waits if necessary for the computation to complete, and then
317     * retrieves its result.
318     *
319     * @return The computed result.
320     *
321     * @throws CancellationException If the computation was cancelled.
322     * @throws ExecutionException If the computation threw an exception.
323     * @throws InterruptedException If the current thread was interrupted
324     *         while waiting.
325     */
326    public final Result get() throws InterruptedException, ExecutionException {
327        return mFuture.get();
328    }
329
330    /**
331     * Waits if necessary for at most the given time for the computation
332     * to complete, and then retrieves its result.
333     *
334     * @param timeout Time to wait before cancelling the operation.
335     * @param unit The time unit for the timeout.
336     *
337     * @return The computed result.
338     *
339     * @throws CancellationException If the computation was cancelled.
340     * @throws ExecutionException If the computation threw an exception.
341     * @throws InterruptedException If the current thread was interrupted
342     *         while waiting.
343     * @throws TimeoutException If the wait timed out.
344     */
345    public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
346            ExecutionException, TimeoutException {
347        return mFuture.get(timeout, unit);
348    }
349
350    /**
351     * Executes the task with the specified parameters. The task returns
352     * itself (this) so that the caller can keep a reference to it.
353     *
354     * <p>Note: this function schedules the task on a queue for a single background
355     * thread or pool of threads depending on the platform version.  When first
356     * introduced, AsyncTasks were executed serially on a single background thread.
357     * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
358     * to a pool of threads allowing multiple tasks to operate in parallel.  After
359     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, it is planned to change this
360     * back to a single thread to avoid common application errors caused
361     * by parallel execution.  If you truly want parallel execution, you can use
362     * the {@link #executeOnExecutor} version of this method
363     * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings on
364     * its use.
365     *
366     * <p>This method must be invoked on the UI thread.
367     *
368     * @param params The parameters of the task.
369     *
370     * @return This instance of AsyncTask.
371     *
372     * @throws IllegalStateException If {@link #getStatus()} returns either
373     *         {@link android.os.AsyncTask.Status#RUNNING} or
374     *          {@link android.os.AsyncTask.Status#FINISHED}.
375     */
376    public final ModernAsyncTask<Params, Progress, Result> execute(Params... params) {
377        return executeOnExecutor(sDefaultExecutor, params);
378    }
379
380    /**
381     * Executes the task with the specified parameters. The task returns
382     * itself (this) so that the caller can keep a reference to it.
383     *
384     * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
385     * allow multiple tasks to run in parallel on a pool of threads managed by
386     * AsyncTask, however you can also use your own {@link Executor} for custom
387     * behavior.
388     *
389     * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
390     * a thread pool is generally <em>not</em> what one wants, because the order
391     * of their operation is not defined.  For example, if these tasks are used
392     * to modify any state in common (such as writing a file due to a button click),
393     * there are no guarantees on the order of the modifications.
394     * Without careful work it is possible in rare cases for the newer version
395     * of the data to be over-written by an older one, leading to obscure data
396     * loss and stability issues.
397     *
398     * <p>This method must be invoked on the UI thread.
399     *
400     * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as a
401     *              convenient process-wide thread pool for tasks that are loosely coupled.
402     * @param params The parameters of the task.
403     *
404     * @return This instance of AsyncTask.
405     *
406     * @throws IllegalStateException If {@link #getStatus()} returns either
407     *         {@link android.os.AsyncTask.Status#RUNNING}
408     *          or {@link android.os.AsyncTask.Status#FINISHED}.
409     */
410    public final ModernAsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
411            Params... params) {
412        if (mStatus != Status.PENDING) {
413            switch (mStatus) {
414                case RUNNING:
415                    throw new IllegalStateException("Cannot execute task:"
416                            + " the task is already running.");
417                case FINISHED:
418                    throw new IllegalStateException("Cannot execute task:"
419                            + " the task has already been executed "
420                            + "(a task can be executed only once)");
421            }
422        }
423
424        mStatus = Status.RUNNING;
425
426        onPreExecute();
427
428        mWorker.mParams = params;
429        exec.execute(mFuture);
430
431        return this;
432    }
433
434    /**
435     * Convenience version of {@link #execute(Object...)} for use with
436     * a simple Runnable object.
437     */
438    public static void execute(Runnable runnable) {
439        sDefaultExecutor.execute(runnable);
440    }
441
442    /**
443     * This method can be invoked from {@link #doInBackground} to
444     * publish updates on the UI thread while the background computation is
445     * still running. Each call to this method will trigger the execution of
446     * {@link #onProgressUpdate} on the UI thread.
447     *
448     * {@link #onProgressUpdate} will note be called if the task has been
449     * canceled.
450     *
451     * @param values The progress values to update the UI with.
452     *
453     * @see #onProgressUpdate
454     * @see #doInBackground
455     */
456    protected final void publishProgress(Progress... values) {
457        if (!isCancelled()) {
458            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
459                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
460        }
461    }
462
463    private void finish(Result result) {
464        if (isCancelled()) {
465            onCancelled(result);
466        } else {
467            onPostExecute(result);
468        }
469        mStatus = Status.FINISHED;
470    }
471
472    private static class InternalHandler extends Handler {
473        public InternalHandler() {
474            super(Looper.getMainLooper());
475        }
476
477        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
478        @Override
479        public void handleMessage(Message msg) {
480            AsyncTaskResult result = (AsyncTaskResult) msg.obj;
481            switch (msg.what) {
482                case MESSAGE_POST_RESULT:
483                    // There is only one result
484                    result.mTask.finish(result.mData[0]);
485                    break;
486                case MESSAGE_POST_PROGRESS:
487                    result.mTask.onProgressUpdate(result.mData);
488                    break;
489            }
490        }
491    }
492
493    private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
494        Params[] mParams;
495    }
496
497    @SuppressWarnings({"RawUseOfParameterizedType"})
498    private static class AsyncTaskResult<Data> {
499        final ModernAsyncTask mTask;
500        final Data[] mData;
501
502        AsyncTaskResult(ModernAsyncTask task, Data... data) {
503            mTask = task;
504            mData = data;
505        }
506    }
507}
508