AsyncTask在Android中是很常用的异步线程,那么AsyncTask和Thread有什么区别呢?这里将从源码角度深入理解AsyncTask的设计和工作原理,这里的AsyncTask
基于SDK-25
分析知识准备
首先我们来看一个生产者与消费者模型的例子
public class ThreadTest { //产品 static class ProductObject{ public volatile static String value; //volatile线程操作变量可见 } //生产者线程 static class Producer extends Thread{ Object lock; public Producer(Object lock) { this.lock = lock; } @Override public void run() { while(true){ synchronized (lock) { if(ProductObject.value != null){ try { lock.wait(); //产品还没有被消费,等待 } catch (InterruptedException e) { e.printStackTrace(); } } ProductObject.value = "NO:"+System.currentTimeMillis(); System.out.println("生产产品:"+ProductObject.value); lock.notify(); //生产完成,通知消费者消费 } } } } //消费者线程 static class Consumer extends Thread{ Object lock; public Consumer(Object lock) { this.lock = lock; } @Override public void run() { while(true){ synchronized (lock) { if(ProductObject.value == null){ try { lock.wait(); //等待,阻塞 } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("消费产品:"+ProductObject.value); ProductObject.value = null; lock.notify(); //消费完成,通知生产者,继续生产 } } } } public static void main(String[] args) { Object lock = new Object(); new Producer(lock).start(); new Consumer(lock).start(); } }
上面的例子关键点在于两个,其一是 volatile
,使得线程间可见,第二个点在于互斥锁,这样就可以使得有商品的时候就要通知消费者消费,同时 wait
,那么消费者收到消息开始消费,消费完毕通知生产者继续生产,从而不断生产,这样比轮询方式更加节省资源
在了解完上面的例子以后,我们就可以着手分析AsyncTask
的源代码了
首先,我们在AsyncTask
首先看其构造方法
private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; ··· public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Result result = null; try { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked result = doInBackground(mParams); Binder.flushPendingCommands(); } catch (Throwable tr) { mCancelled.set(true); throw tr; } finally { postResult(result); } return result; } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occurred while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; }
这里首先给WorkerRunnable
和Future
进行了初始化,那么为何要初始化这两个变量呢?
这里就要说到常用的两个方法了,doInBackground()
,这个方法是在子线程里面完成的,另一个方法就是onPostExecute()
,而这个方法是存在于主线程的,那么也就是说子线程执行完将执行的结果传递到了主线程中,实现了线程间的通信,那么最关键的问题来了,这个通信是怎么实现的呢?
通常在子线程中执行的任务,是没有返回结果的,例如Runnable
的源代码如下,就没有返回结果
public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
那么,要怎么才能得到返回值呢,这里首先想到的就是Callable
接口,那么再看看Callable
的源代码
@FunctionalInterface public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }
可以看到,这是一个泛型方法,是有返回值的,但是其本身确是不能直接执行的,需要借助其他类,接下来再看一看源代码中涉及到的Future
接口
public interface Future<V> { /** * Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, has already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when {@code cancel} is called, * this task should never run. If the task has already started, * then the {@code mayInterruptIfRunning} parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task. * * <p>After this method returns, subsequent calls to {@link #isDone} will * always return {@code true}. Subsequent calls to {@link #isCancelled} * will always return {@code true} if this method returned {@code true}. * * @param mayInterruptIfRunning {@code true} if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete * @return {@code false} if the task could not be cancelled, * typically because it has already completed normally; * {@code true} otherwise */ boolean cancel(boolean mayInterruptIfRunning); /** * Returns {@code true} if this task was cancelled before it completed * normally. * * @return {@code true} if this task was cancelled before it completed */ boolean isCancelled(); /** * Returns {@code true} if this task completed. * * Completion may be due to normal termination, an exception, or * cancellation -- in all of these cases, this method will return * {@code true}. * * @return {@code true} if this task completed */ boolean isDone(); /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return the computed result * @throws CancellationException if the computation was cancelled * @throws ExecutionException if the computation threw an * exception * @throws InterruptedException if the current thread was interrupted * while waiting */ V get() throws InterruptedException, ExecutionException; /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result, if available. * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return the computed result * @throws CancellationException if the computation was cancelled * @throws ExecutionException if the computation threw an * exception * @throws InterruptedException if the current thread was interrupted * while waiting * @throws TimeoutException if the wait timed out */ V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
在Future
类中,有好几个方法,而这些方法都是有返回值的,那么Runnable
与Future
和FutureTask
有什么关系呢,产看源码便可得知,FutureTask
实际上是实现了RunnableFuture
接口
public class FutureTask<V> implements RunnableFuture<V>{ ··· }
而RunnableFuture
又继承了Runnable
和Future
public interface RunnableFuture<V> extends Runnable, Future<V> { void run(); }
那也就是说,FutureTask
既可以在子线程中执行,也可以获得执行结果,下面使用一个例子来说明FutureTask
public class FutureTest { public static void main(String[] args) { Task work = new Task(); FutureTask<Integer> future = new FutureTask<Integer>(work){ @Override protected void done() { //异步任务执行完成,回调 try { System.out.println("done:" + get()); //get()获取异步任务的返回值,这是个阻塞方法 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }; //线程池(使用了预定义的配置) ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(future); } //异步任务 static class Task implements Callable<Integer>{ @Override public Integer call() throws Exception {//返回异步任务的执行结果 int i = 0; for (; i < 10; i++) { try { System.out.println(Thread.currentThread().getName() + "_" + i); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } return i; } } }
上面的例子可以看出,在使用了Callable
的时候,需要借助FutureTask
来包装,然后使用Executor
的execute()
方法来执行,那么是怎么得到异步任务的返回值呢,在上面的例子中,我们可以看到,其返回值的获取是通过future.get()
得到的,然而这个get()
方法确是被阻塞的,只有在异步任务完成的时候才能获取到其结果,那我们怎么才能知道异步任务时候执行完毕呢,这里就可以实现FutureTask
的done()
方法,当异步任务执行完毕以后会回调这个方法,上述例子其实解释了AsyncTask
的实现逻辑,call()
方法是在子线程中完成,这也就是doInBackground()
的实现,在主线程中获得结果,这是在onPostExecute()
使用了get()
方法,那也就是说AsyncTask
就是通过这一套方法去实现的
从这里我们可以总结出FutureTask
为异步任务提供了诸多便利性,包括
- 获取异步任务的返回值
- 监听异步任务的执行情况
- 取消异步任务
那么在AsyncTask
中,WorkerRunnable
又是啥呢,其实就是一个内部类,对Callable
进行了封装
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; }
源代码分析
有了以上知识储备,我们就可以动手分析AsyncTask
源代码了
拿到源代码,不同的人有不同的分析习惯,这里我按照我的习惯对源代码进行一次分析
构造方法分析
首先,因为我们分析源代码是为了更好的去使用,而使用的话,第一个关注的就应该是构造方法,回到之前的的构造方法,这里要开始对构造方法开始入手分析了
private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private final AtomicBoolean mCancelled = new AtomicBoolean(); private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); ··· public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { //设置线程调用 mTaskInvoked.set(true); Result result = null; try { //设置线程优先级,其给定值为10 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //调用doInBackground()方法得到返回值 result = doInBackground(mParams); //将当前线程中的Binder命令发送至kernel Binder.flushPendingCommands(); } catch (Throwable tr) { //发生异常则取消线程调用设置 mCancelled.set(true); throw tr; } finally { //执行postResult()方法 postResult(result); } return result; } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { //执行postResultIfNotInvoked()方法 postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occurred while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; }
以上就是AsyncTask
的构造方法了,在构造方法上有一句说明,这个构造方法必须在UI线程中创建,这一点很好理解,因为其有需要再主线程中执行的地方,后面会说到,那么这个构造方法干了什么事情呢,很简单,这里新建了两个对象,首先是WorkerRunnable
,而这个WorkerRunnable
则是实现自Callable
接口,主要是要使用其call()
方法,为了返回参数,并没有什么特别之处,再其内部则实现了call()
方法,而其自生是无法执行的,需要找一个包装类,而这个包装类就是FutureTask
,通过之前的分析,这里就不再多赘述关于FutureTask
的东西了,这里实现了done()
方法,也就是线程执行完毕调用的方法,简单点来说就是在call()
方法中执行,在done()
中获得执行的返回结果,上述涉及到一个内部类和三个自定义的方法,那么接下来我们看一看这个内部类和三个方法都干了啥
构造方法中出现的内部类
这里的WorkerRunnable
,正如前面所说,这里除了实现Callable
就啥也没干,还是个抽象方法,这里将实现放在了构造方法中
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; }
构造方法中调用的方法
首先是doInBackground()
方法,前面讲到,这个方法在子线程中完成,那么这里的子线程是哪个呢,其实就是WorkerThread
,这个方法是一个抽象方法,放在子线程中执行,其具体实现由调用者完成
@WorkerThread protected abstract Result doInBackground(Params... params);
再看postResult()
方法,这里获取了一个Handler
,然后发送了一个消息,这里就是子线程能够通信主线程的地方了
private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; }
那么到这里,我们关注的重点就来了,子线程是怎么告诉主线程的呢,要知道其中的原因,我们就需要去看看代码里面是怎么实现的
我们先看发送了什么消息,也就是AsyncTaskResult
里面干了啥,查看代码发现,其就是做了参数传递的任务
@SuppressWarnings({"RawUseOfParameterizedType"}) private static class AsyncTaskResult<Data> { final AsyncTask mTask; final Data[] mData; AsyncTaskResult(AsyncTask task, Data... data) { mTask = task; mData = data; } }
那么接下来的重点就是getHandler()
方法了,这里拿到AsyncTask.class
就上了锁了,这也很好理解,不上锁其他线程走到这里会产生安全隐患,然后返回sHandler
,那再继续看看InternalHandler
又是个什么吧
private static InternalHandler sHandler; ··· private static Handler getHandler() { synchronized (AsyncTask.class) { if (sHandler == null) { sHandler = new InternalHandler(); } return sHandler; } }
这里就是了,在构造方法里面super(Looper.getMainLooper())
,也就说明了这个方法是在主线程中执行的,在主线程中对Message
进行处理,这里又涉及到两个方法,一个是finish()
,还有一个是onProgressUpdate()
,那么好吧,再去看看这两个方法在干啥
private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; ··· private static class InternalHandler extends Handler { public InternalHandler() { super(Looper.getMainLooper()); } @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; } } }
首先是又调了isCancelled()
,判断是否取消,前面构造函数的时候见过这个,这是在异常发生的时候才设置为true
的,那么如果不发生异常,这里应该就是为false
的,但在找源代码时发现,另一个方法也对这个参数进行了设置,那就是cancel()
,所以在不发生异常和取消的时候应该是为true
的,接下来是onCancelled()
方法,这里是不做任何操作的,这也是主线程中的方法,还有就是onPostExecute()
方法,然后会设置状态,其默认状态是PENDING
private volatile Status mStatus = Status.PENDING; ··· public enum Status { PENDING, RUNNING, FINISHED, } ··· private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } @SuppressWarnings({"UnusedDeclaration"}) @MainThread protected void onPostExecute(Result result) { } @SuppressWarnings({"UnusedParameters"}) @MainThread protected void onCancelled(Result result) { onCancelled(); } @MainThread protected void onCancelled() { } public final boolean isCancelled() { return mCancelled.get(); } ··· public final boolean cancel(boolean mayInterruptIfRunning) { mCancelled.set(true); return mFuture.cancel(mayInterruptIfRunning); }
然后是onProgressUpdate()
方法,那么这里做了啥呢,嗯~啥也没有,交给调用者在继承时可以使用
@SuppressWarnings({"UnusedDeclaration"}) @MainThread protected void onProgressUpdate(Progress... values) { }
来看构造方法中涉及到的最后一个方法postResultIfNotInvoked()
,这个方法又干了啥了,首先获得了mTaskInvoked
的状态,整个AsyncTask
只有构造方法处设置了这个值,然后判断是否执行postResult()
方法
private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); if (!wasTaskInvoked) { postResult(result); } }
至此构造方法分析完成,可以看到在构造方法中,其主要做的工作最主要的就是搭建好了子线程和主线程沟通的桥梁
执行入口分析
在新建AsyncTask
对象以后,要执行的话,需要使用execute()
去开始执行
那么我们就从这里入手,看看其具体是怎么工作的,可以看到无论是构造方法还是启动方法,都是需要在主线程中完成的,在execute()
中,做了些什么呢,在这之前我们先看看传递的sDefaultExecutor
是啥
@MainThread public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); }
这其实是一个线程池,任务调度的线程池,可以看到SerialExecutor
实际上是实现了Executor
接口,其作用就是将任务添加到双向队列,然后不断地取出执行取出执行,那么THREAD_POOL_EXECUTOR
也应该是一个线程池,那这又是啥呢,去看一看这个玩意儿就是到了
public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; ··· private static class SerialExecutor implements Executor { //定义了一个双向队列,用来存储线程 final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); Runnable mActive; public synchronized void execute(final Runnable r) { //向队列中添加线程 mTasks.offer(new Runnable() { public void run() { try { //线程运行 r.run(); } finally { //执行scheduleNext()方法 scheduleNext(); } } }); if (mActive == null) { scheduleNext(); } } //从队列中取出线程并执行 protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } } }
下列代码就是初始化了线程池的参数,指定了线程数量
//获得可用CPU数量 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); //设置核心线程池数量其范围[2,4],无论是否使用都存在 private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4)); //设置最大线程数量 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; //设置闲置回收时间,也就是说线程在这个时间内没有活动的话,会被回收 private static final int KEEP_ALIVE_SECONDS = 30; //设置线程工厂,通过这个创建线程 private static final ThreadFactory sThreadFactory = new ThreadFactory() { //创建线程安全的线程个数计数器 private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; //设置任务队列大小 private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128); //设置线程池 public static final Executor THREAD_POOL_EXECUTOR; //初始化线程池 static { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); //打开核心线程池的超时时间 threadPoolExecutor.allowCoreThreadTimeOut(true); THREAD_POOL_EXECUTOR = threadPoolExecutor; }
所以在执行scheduleNext()
的时候,会将THREAD_POOL_EXECUTOR
中设置好的线程全部取出来,用来执行后面的任务,其执行的任务就是execute()
方法所指定的任务,在executeOnExecutor()
方法中,由于前面初始化完成,这里的状态应该是PENDING
,之后还设置了mWorker
的参数,然后会执行线程池的方法,然后据开始执行任务了,前面没有涉及到的方法还有一个,那我们接下来看看
@MainThread public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); return this; }
onPreExecute()
,这个方法由调用者在继承时候能够使用
@MainThread protected void onPreExecute() { }
至此,AsyncTask
的执行方法也分析完了,那么我们接下来看看还有什么方法没有涉及到,没有涉及到的方法都是public
属性和方法
AsyncTask的公共方法
//这个方法设置为public,那么就意味着我们可以自定义线程池 public static void setDefaultExecutor(Executor exec) { sDefaultExecutor = exec; }
//这个方法意味着我们可以获得其状态,配合枚举值使用 public enum Status { PENDING, RUNNING, FINISHED, } ··· public final Status getStatus() { return mStatus; }
//查看是非被取消 public final boolean isCancelled() { return mCancelled.get(); }
//取消异步任务 public final boolean cancel(boolean mayInterruptIfRunning) { mCancelled.set(true); return mFuture.cancel(mayInterruptIfRunning); }
//获取返回结果,注意:这个方法是阻塞式的 public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); }
//同上 public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); }
//自定义的线程池可以从这个方法启动 @MainThread public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); return this; }
//使用默认线程池启动异步任务 @MainThread public static void execute(Runnable runnable) { sDefaultExecutor.execute(runnable); }
总结
AsyncTask
的实例化过程,其本质上就是实例化了一个FutureTask
其执行过程Executor.execute(mFuture)
-> SerialExecutor.mTasks(队列)
-> (线程池)THREAD_POOL_EXECUTOR.execute
线程池中的所有线程,为了执行异步任务
如果当前线程池中的数量小于corePoolSize
,创建并添加的任务
如果当前线程池中的数量等于corePoolSize
,缓冲队列workQueue
未满,那么任务被放入缓冲队列、等待任务调度执行
如果当前线程池中的数量大于corePoolSize
,缓冲队列workQueue
已满,并且线程池中的数量小于maximumPoolSize
,新提交任务会创建新线程执行任务
如果当前线程池中的数量大于corePoolSize
,缓冲队列workQueue
已满,并且线程池中的数量等于maximumPoolSize
,新提交任务由Handler
处理
当线程池中的线程大于corePoolSize
时,多余线程空闲时间超过keepAliveTime
时,会关闭这部分线程
线程池在添加时候是串行的,在执行任务的时候是并行的
附录(源代码)
package android.os; import android.annotation.MainThread; import android.annotation.WorkerThread; import java.util.ArrayDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * <p>AsyncTask enables proper and easy use of the UI thread. This class allows you * to perform background operations and publish results on the UI thread without * having to manipulate threads and/or handlers.</p> * * <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler} * and does not constitute a generic threading framework. AsyncTasks should ideally be * used for short operations (a few seconds at the most.) If you need to keep threads * running for long periods of time, it is highly recommended you use the various APIs * provided by the <code>java.util.concurrent</code> package such as {@link Executor}, * {@link ThreadPoolExecutor} and {@link FutureTask}.</p> * * <p>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 * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>, * and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>, * <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p> * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about using tasks and threads, read the * <a href="{@docRoot}guide/components/processes-and-threads.html">Processes and * Threads</a> developer guide.</p> * </div> * * <h2>Usage</h2> * <p>AsyncTask must be subclassed to be used. The subclass will override at least * one method ({@link #doInBackground}), and most often will override a * second one ({@link #onPostExecute}.)</p> * * <p>Here is an example of subclassing:</p> * <pre class="prettyprint"> * private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { * protected Long doInBackground(URL... urls) { * int count = urls.length; * long totalSize = 0; * for (int i = 0; i < count; i++) { * totalSize += Downloader.downloadFile(urls[i]); * publishProgress((int) ((i / (float) count) * 100)); * // Escape early if cancel() is called * if (isCancelled()) break; * } * return totalSize; * } * * protected void onProgressUpdate(Integer... progress) { * setProgressPercent(progress[0]); * } * * protected void onPostExecute(Long result) { * showDialog("Downloaded " + result + " bytes"); * } * } * </pre> * * <p>Once created, a task is executed very simply:</p> * <pre class="prettyprint"> * new DownloadFilesTask().execute(url1, url2, url3); * </pre> * * <h2>AsyncTask's generic types</h2> * <p>The three types used by an asynchronous task are the following:</p> * <ol> * <li><code>Params</code>, the type of the parameters sent to the task upon * execution.</li> * <li><code>Progress</code>, the type of the progress units published during * the background computation.</li> * <li><code>Result</code>, the type of the result of the background * computation.</li> * </ol> * <p>Not all types are always used by an asynchronous task. To mark a type as unused, * simply use the type {@link Void}:</p> * <pre> * private class MyTask extends AsyncTask<Void, Void, Void> { ... } * </pre> * * <h2>The 4 steps</h2> * <p>When an asynchronous task is executed, the task goes through 4 steps:</p> * <ol> * <li>{@link #onPreExecute()}, invoked on the UI thread before the task * is executed. This step is normally used to setup the task, for instance by * showing a progress bar in the user interface.</li> * <li>{@link #doInBackground}, invoked on the background thread * immediately after {@link #onPreExecute()} finishes executing. This step is used * to perform background computation that can take a long time. The parameters * 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 * {@link #onProgressUpdate} step.</li> * <li>{@link #onProgressUpdate}, invoked on the UI 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.</li> * <li>{@link #onPostExecute}, invoked on the UI thread after the background * computation finishes. The result of the background computation is passed to * this step as a parameter.</li> * </ol> * * <h2>Cancelling a task</h2> * <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking * this method will cause subsequent calls to {@link #isCancelled()} to return true. * After invoking this method, {@link #onCancelled(Object)}, instead of * {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])} * returns. To ensure that a task is cancelled as quickly as possible, you should always * check the return value of {@link #isCancelled()} periodically from * {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p> * * <h2>Threading rules</h2> * <p>There are a few threading rules that must be followed for this class to * work properly:</p> * <ul> * <li>The AsyncTask class must be loaded on the UI thread. This is done * automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li> * <li>The task instance must be created on the UI thread.</li> * <li>{@link #execute} must be invoked on the UI thread.</li> * <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute}, * {@link #doInBackground}, {@link #onProgressUpdate} manually.</li> * <li>The task can be executed only once (an exception will be thrown if * a second execution is attempted.)</li> * </ul> * * <h2>Memory observability</h2> * <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following * operations are safe without explicit synchronizations.</p> * <ul> * <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them * in {@link #doInBackground}. * <li>Set member fields in {@link #doInBackground}, and refer to them in * {@link #onProgressUpdate} and {@link #onPostExecute}. * </ul> * * <h2>Order of execution</h2> * <p>When first introduced, AsyncTasks were executed serially on a single background * thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed * to a pool of threads allowing multiple tasks to operate in parallel. Starting with * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single * thread to avoid common application errors caused by parallel execution.</p> * <p>If you truly want parallel execution, you can invoke * {@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with * {@link #THREAD_POOL_EXECUTOR}.</p> */ public abstract class AsyncTask<Params, Progress, Result> { private static final String LOG_TAG = "AsyncTask"; private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); // We want at least 2 threads and at most 4 threads in the core pool, // preferring to have 1 less than the CPU count to avoid saturating // the CPU with background work private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4)); private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; private static final int KEEP_ALIVE_SECONDS = 30; private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128); /** * An {@link Executor} that can be used to execute tasks in parallel. */ public static final Executor THREAD_POOL_EXECUTOR; static { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); threadPoolExecutor.allowCoreThreadTimeOut(true); THREAD_POOL_EXECUTOR = threadPoolExecutor; } /** * An {@link Executor} that executes tasks one at a time in serial * order. This serialization is global to a particular process. */ public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; private static InternalHandler sHandler; private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; private final AtomicBoolean mCancelled = new AtomicBoolean(); private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); private static class SerialExecutor implements Executor { final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); Runnable mActive; public synchronized void execute(final Runnable r) { mTasks.offer(new Runnable() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (mActive == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } } } /** * Indicates the current status of the task. Each status will be set only once * during the lifetime of a task. */ public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link AsyncTask#onPostExecute} has finished. */ FINISHED, } private static Handler getHandler() { synchronized (AsyncTask.class) { if (sHandler == null) { sHandler = new InternalHandler(); } return sHandler; } } /** @hide */ public static void setDefaultExecutor(Executor exec) { sDefaultExecutor = exec; } /** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Result result = null; try { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked result = doInBackground(mParams); Binder.flushPendingCommands(); } catch (Throwable tr) { mCancelled.set(true); throw tr; } finally { postResult(result); } return result; } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occurred while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; } private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); if (!wasTaskInvoked) { postResult(result); } } private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; } /** * Returns the current status of this task. * * @return The current status. */ public final Status getStatus() { return mStatus; } /** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} * by the caller of this task. * * This method can call {@link #publishProgress} to publish updates * on the UI thread. * * @param params The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress */ @WorkerThread protected abstract Result doInBackground(Params... params); /** * Runs on the UI thread before {@link #doInBackground}. * * @see #onPostExecute * @see #doInBackground */ @MainThread protected void onPreExecute() { } /** * <p>Runs on the UI thread after {@link #doInBackground}. The * specified result is the value returned by {@link #doInBackground}.</p> * * <p>This method won't be invoked if the task was cancelled.</p> * * @param result The result of the operation computed by {@link #doInBackground}. * * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */ @SuppressWarnings({"UnusedDeclaration"}) @MainThread protected void onPostExecute(Result result) { } /** * Runs on the UI thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values The values indicating progress. * * @see #publishProgress * @see #doInBackground */ @SuppressWarnings({"UnusedDeclaration"}) @MainThread protected void onProgressUpdate(Progress... values) { } /** * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.</p> * * <p>The default implementation simply invokes {@link #onCancelled()} and * ignores the result. If you write your own implementation, do not call * <code>super.onCancelled(result)</code>.</p> * * @param result The result, if any, computed in * {@link #doInBackground(Object[])}, can be null * * @see #cancel(boolean) * @see #isCancelled() */ @SuppressWarnings({"UnusedParameters"}) @MainThread protected void onCancelled(Result result) { onCancelled(); } /** * <p>Applications should preferably override {@link #onCancelled(Object)}. * This method is invoked by the default implementation of * {@link #onCancelled(Object)}.</p> * * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.</p> * * @see #onCancelled(Object) * @see #cancel(boolean) * @see #isCancelled() */ @MainThread protected void onCancelled() { } /** * Returns <tt>true</tt> if this task was cancelled before it completed * normally. If you are calling {@link #cancel(boolean)} on the task, * the value returned by this method should be checked periodically from * {@link #doInBackground(Object[])} to end the task as soon as possible. * * @return <tt>true</tt> if task was cancelled before it completed * * @see #cancel(boolean) */ public final boolean isCancelled() { return mCancelled.get(); } /** * <p>Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when <tt>cancel</tt> is called, * this task should never run. If the task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task.</p> * * <p>Calling this method will result in {@link #onCancelled(Object)} being * invoked on the UI 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 * {@link #doInBackground(Object[])} to finish the task as early as * possible.</p> * * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. * * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; * <tt>true</tt> otherwise * * @see #isCancelled() * @see #onCancelled(Object) */ public final boolean cancel(boolean mayInterruptIfRunning) { mCancelled.set(true); return mFuture.cancel(mayInterruptIfRunning); } /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result. * * @param timeout Time to wait before cancelling the operation. * @param unit The time unit for the timeout. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. * @throws TimeoutException If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p>Note: this function schedules the task on a queue for a single background * thread or pool of threads depending on the platform version. When first * introduced, AsyncTasks were executed serially on a single background thread. * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed * to a pool of threads allowing multiple tasks to operate in parallel. Starting * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being * executed on a single thread to avoid common application errors caused * by parallel execution. If you truly want parallel execution, you can use * the {@link #executeOnExecutor} version of this method * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings * on its use. * * <p>This method must be invoked on the UI 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}. * * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) * @see #execute(Runnable) */ @MainThread public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to * allow multiple tasks to run in parallel on a pool of threads managed by * AsyncTask, however you can also use your own {@link Executor} for custom * behavior. * * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from * a thread pool is generally <em>not</em> what one wants, because the order * of their operation is not defined. For example, if these tasks are used * to modify any state in common (such as writing a file due to a button click), * there are no guarantees on the order of the modifications. * Without careful work it is possible in rare cases for the newer version * of the data to be over-written by an older one, leading to obscure data * loss and stability issues. Such changes are best * executed in serial; to guarantee such work is serialized regardless of * platform version you can use this function with {@link #SERIAL_EXECUTOR}. * * <p>This method must be invoked on the UI 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. * @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}. * * @see #execute(Object[]) */ @MainThread public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); return this; } /** * Convenience version of {@link #execute(Object...)} for use with * a simple Runnable object. See {@link #execute(Object[])} for more * information on the order of execution. * * @see #execute(Object[]) * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) */ @MainThread public static void execute(Runnable runnable) { sDefaultExecutor.execute(runnable); } /** * This method can be invoked from {@link #doInBackground} to * publish updates on the UI 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} will not be called if the task has been * canceled. * * @param values The progress values to update the UI with. * * @see #onProgressUpdate * @see #doInBackground */ @WorkerThread protected final void publishProgress(Progress... values) { if (!isCancelled()) { getHandler().obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget(); } } private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } private static class InternalHandler extends Handler { public InternalHandler() { super(Looper.getMainLooper()); } @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; } } } private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } @SuppressWarnings({"RawUseOfParameterizedType"}) private static class AsyncTaskResult<Data> { final AsyncTask mTask; final Data[] mData; AsyncTaskResult(AsyncTask task, Data... data) { mTask = task; mData = data; } } }