原理:
在使用AsyncTask时,一般会继承AsyncTask并重写doInBackground方法,onPostExecute方法,在doInBackground方法中做耗时操作,在onPostExecute方法中更新UI。常见的泄露的场景是,当Activity onDestroy方法回调后,AsyncTask的方法没有执行完成,或者是在doInBackground方法中,或者是在onPostExecute方法中,而AsyncTask持有Activity的引用(一般是非静态内部类持有外部类的引用和匿名内存类持有外部类的引用两种形式),导致Activity无法及时回收,从而导致内存泄露。
AsyncTask的设计其实是对Handler+Thread的封装,AsyncTask的运行是通过调用execute方法,运行背后是有一个线程池。
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);
// AsyncTask的执行默认是靠sDefaultExecutor的调度
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
sDefaultExecutor在AsyncTask中是以常量形式存在,所有AsyncTask的实例公用一个sDefaultExecutor,在AsyncTask叫SERIAL_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();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
SerialExecutor使用双端队列ArrayDeque管理Runnable对象,如果一次性启动了多个任务,首先第一个Task执行execute方法时,调用ArrayDeque的offer将传入的Runnable对象添加至队列尾部,然后判断mActive是否为null,第一次运行时为null,会调用scheduleNext方法,在scheduleNext方法中赋值mActive,通过THREAD_POOL_EXECUTOR调度,之后再有新的任务被执行时,同样会调用offer方法将传入的Runnable对象添加至队列的尾部,但此时mActive不在为null,于是不会执行scheduleNext方法,也就是说不会得到立即执行,那什么时候会执行呢?看finally中,同样会调用scheduleNext方法,也就是说,当此Task执行完成后,会去执行下一个Task,SerialExecutor模仿的是单一线程池的效果,如果我们快速地启动了很多任务,同一时刻只会有一个线程正在执行,其余的均处于等待状态。
假设用户开启某个页面,而此页面有Task在执行,再打开另外一个页面,这个页面还有Task需要执行,这个时候很可能会出现卡一个的情况,不是硬件配置差,而是软件质量差导致的。
修复:
1: cancel + isCancelled
2:建议在修复方案1的基础上将AsyncTask作为静态内部类存在(与Handler处理方式相似),避免内部类的this$0持有外部类的引用但不推荐只修改AsyncTask为静态内部类的方案,虽然不是泄露了,但没有根本上解决问题~
3:如果AsyncTask中需要使用Context,建议使用weakreference
cancel方法可能不会得到立即执行,在接口调用处也有如下说明:
/**
* <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);
}
如果任务没有运行且cancel方法被调用,那么任务会被立即取消且确保不会被执行,当任务已经启动了,mayInterruptIfRunning参数决定是否尝试去停止Task。调用cancel方法能确保onPostdExecute方法不会被执行,执行了cancel方法,不会立即终止任务,会等doInBackground方法执行完成后返回,然后定期通过调用isCancelled方法检查task状态尽早的结束task。意思是,AsyncTask不会立即结束一个正在运行的线程,调用cancel方法只是给AsyncTask设置了"cancelled"状态,并不是停止Task,那么有人说是不是由mayInterruptIfRunning参数来控制?其实mayInterruptIfRunning只是执行线程的interrupt方法,并不是真正的中断线程,而是通知线程应该中断了~
简单说下线程的interrupt:
1,如果线程处于被阻塞状态(例如处于sleep, wait, join 等状态),那么线程将立即退出被阻塞状态,并抛出一个InterruptedException例外。
2,如果线程处于正常活动状态,那么会将该线程的中断标志设置为 true(isInterrupted() == true)仅此而已。被设置中断标志的线程将继续正常运行,不受影响。
真正决定任务取消的是需要手动调用isCancelled方法check task状态,因此推荐的修复方案是在手动调用cancel方法的同时,能调用inCancelled方法检测task状态:
@Override
protected Integer doInBackground(Void... mgs) {
// Task被取消了,马上退出
if(isCancelled()) return null;
.......
// Task被取消了,马上退出
if(isCancelled()) return null;
}
...