AsyncTask源码分析

导语:最近项目中使用AsyncTask遇到一个坑,特此机会随便看了一下Asynctask的源码。
项目中之前对页面数据做本地缓存,读写缓存时是用了AsyncTask做了异步操作:

    public void getCache(String key, final Class type, final OnCacheListener onCacheListener) {
        if (!TextUtils.isEmpty(key)) {
            new AsyncTask() {

                @Override
                protected Rsp doInBackground(String... strings) {
                     //读缓存...
                    return result;
                }

                @Override
                protected void onPostExecute(Rsp result) {
                    super.onPostExecute(result);
                    if (result != null && onCacheListener != null) {
                        onCacheListener.onCache(result);
                    }
                }
            }.execute(key);
        }
    }

可是最近发现首页加载比较慢,跟踪发现首页业务层读缓存有将近500ms的耗时,和之前测得的的40ms左右相差了有10倍多,明显不合理。打印日志一看,发现读缓存时AsyncTask.doInBackground()方法要要等待很久才会执行。这时我才想起,AsyncTask.execute()方法虽然是4个线程池的,但是其内部却实现的按调用execute()顺序依次回调onPostExecute()(其实这理解有偏差,下面会有说明)。首页刚启动时,由于请求的接口(接口请求底层也是用AsyncTask实现异步操作)比较多,而读缓存的AsyncTask调用比较晚,自然会被其他地方调用的AsyncTask阻塞了。
这个问题比较好解决,读缓存时改成调用AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, key)方法,或改用Handler方式实现异步操作就能解决。虽然问题解决了,但AsyncTask这么基础的东西,自己使用时还是遇到了坑(与其说是坑,不如说是自己了解得不够透彻,使用不合理),这样让我不得不翻看AsyncTask的源码,一看究竟。
源码分析(基于Android SDK 28)
AsyncTask最基础的使用方式是new AsyncTask().execute(),我们先看看execute()方法。

    public final AsyncTask execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }
    public final AsyncTask 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;
    }

可以看到execute()内部也是调用executeOnExecutor()方法,传递一个默认的sDefaultExecutor。executeOnExecutor()方法中首先做了mStatus状态的判断,也就是为什么一个AsyncTask实例多次调用execute()方法会报IllegalStateException。接着是调用我们熟悉的onPreExecute()方法,这个方法运行在主线程,一般用于执行doInBackground()前在这个方法里做一些UI处理,比如show一个Dialog。最后会将params赋值给mWorker.mParams,调动exec.execute(mFuture)
那mWorker和mFuture到底是什么呢?我们先看看它们是在哪里初始化的?
可以看到mWorker和mFuture都是在AsyncTask的构造函数中初始化的:

    public AsyncTask() {
        this((Looper) null);
    }

    public AsyncTask(@Nullable Looper callbackLooper) {
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

        mWorker = new WorkerRunnable() {
            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(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 static Handler getMainHandler() {
        synchronized (AsyncTask.class) {
            if (sHandler == null) {
                sHandler = new InternalHandler(Looper.getMainLooper());
            }
            return sHandler;
        }
    }

AsyncTask构造函数,首先调用getMainHandler()初始化了一个Handler(InternalHandler)成员变量。mWorker的call()方法中,我们看到我们熟悉doInBackground(),调用doInBackground得到结果result,最后在finally中调用并调用postResult(),我们看看postResult()代码:

    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult(this, result));
        message.sendToTarget();
        return result;
    }

    private Handler getHandler() {
        return mHandler;
    }
    private static class InternalHandler extends Handler {
        public InternalHandler(Looper looper) {
            super(looper);
        }

        @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 void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

我们可以看到postResult()中通过mHandler把Result发送到InternalHandler的handleMessage(),然后调用finish()方法。在finish()方法中,如果没有isCancelled()取消,则回调到我们熟悉的onPostExecute()中,并将状态置为FINISHED。
因此,可以看到其实AsyncTask内部线程通信也是用Handler实现的。
接着看mFuture,mFuture是FutureTask实例,实现了Runnable接口。用mWorker作为参数实现了初始化(这点很关键,后面会提到)

public class FutureTask implements RunnableFuture {
}

public interface RunnableFuture extends Runnable, Future {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

找到了调用doInBackground()的代码,那doInBackground()是怎么运行在子线程中的呢?带着疑惑,我接着exec.execute(mFuture)内部实现。

    public final AsyncTask execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

    private static class SerialExecutor implements Executor {
        final ArrayDeque mTasks = new ArrayDeque();
        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);
            }
        }
    }

我们调用new AsyncTask().execute()时,其实是调用executeOnExecutor(),传递一个默认的sDefaultExecutor。而sDefaultExecutor其实是SerialExecutor对象。可以看到SerialExecutor内部维持了一个任务队列,在execute()方法中首先new一个Runnable放入mTasks队尾,然后判断当前mActive是否为空,如果不为空在调用scheduleNext()方法。在scheduleNext()方法中首先取出任务队列mTasks中的队首任务,如果不为null则赋值给mActive对象并传入THREAD_POOL_EXECUTOR进行执行。
THREAD_POOL_EXECUTOR我们也很熟悉,就是我刚开始提到了4个线程池。这里可以看到execute()其实是和THREAD_POOL_EXECUTOR共用一个线程池的。
接着我们看看THREAD_POOL_EXECUTOR的实现:

    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;
    }
    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 sPoolWorkQueue =
            new LinkedBlockingQueue(128);

可以看到THREAD_POOL_EXECUTOR其实就是一个线程池。数量跟CPU的核数有关,线程数最少2个,最多4个,线程存活时间为30秒。这里纠正了刚开始提到的4个线程池,其实线程数量跟CPU核数有关。
我们接着看看THREAD_POOL_EXECUTOR.execute()内部实现(代码量有点多,做了省略):

    public void execute(Runnable command) {
      //省略...
      addWorker(command, true)
       //省略...
    }

    private boolean addWorker(Runnable firstTask, boolean core) {
        //省略...
        w = new Worker(firstTask);
        //省略...
        return workerStarted;
    }

     Worker(Runnable firstTask) {
          setState(-1);
          this.firstTask = firstTask;
          this.thread = getThreadFactory().newThread(this);
    }

可以看到,THREAD_POOL_EXECUTOR.execute()内部会调用sThreadFactory.newThread()创建新线程运行mTask任务队列里的Runnable,也就是运行了mFuture.run()。
看到这里可能有点乱了,我们重新梳理一下。
我们上面有提到doInBackground是在mWorker的call方法中调用的,所以我们找mWorker.call()的调用地方。

        mWorker = new WorkerRunnable() {
            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;
            }
        };

由于在executeOnExecutor()方法中,mWorker是以参数传递到mFuture中的,所以看一下FutureTask源码是否有调用mWorker.call()。

public class FutureTask implements RunnableFuture {
    public void run() {
        if (state != NEW ||
            !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
            return;
        try {
            Callable c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
}

果然,在mFuture的run方法找到了result = c.call(),也就是调用了mWork的call()方法。
接着mFuture作为参数传递给了SerialExecutor.execute(),而在SerialExecutorSerialExecutor.execute()方法中通过THREAD_POOL_EXECUTOR创建子线程最终调用mFuture.run()。也就是解释了为什么doInBackground是运行在子线程中的了。 r.run()执行完后finally继续调用scheduleNext(),保证了mTasks任务按execute()顺序执行。

 private static class SerialExecutor implements Executor {
        final ArrayDeque mTasks = new ArrayDeque();
        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);
            }
        }
    }

总结:
1.AsyncTask内部也是用Handler实现线程间通信
2.AsyncTask.execute()和AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, key)内部其实用的是同一个线程池。
3.THREAD_POOL_EXECUTOR线程池线程数量跟CPU核数有关,最少2个,最多4个,线程存活时间30秒。
End

你可能感兴趣的:(AsyncTask源码分析)