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