Monday, March 9, 2015

Parallel AsyncTask

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

That means, if you want to run a batch of network operations, which need to be performed in exact order, that behavior might come in handy. But, if you intend to run independent tasks, you may end up waiting some time for the previous tasks to finish. And that is the case to execute your tasks on a ThereadPoolExecutor, allowing them to run in parallel.

Since I believe, everyone is targeting API >= 4 now, you can use following code to execute AsyncTask in parallel. Note that for parallel execution, you must call parallelExecute(), or else the execution will be API dependent.

public abstract class ParallelAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

    /**
     * Executes the task with the specified parameters. Use instead of execute().
     *
     * @param params The parameters of the task.
     * @return This instance of AsyncTask.
     */
    public final AsyncTask<Params, Progress, Result> parallelExecute(Params... params) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            return executeOnExecutor(THREAD_POOL_EXECUTOR, params);
        } else {
            return execute(params);
        }
    }
}

0 comments:

Post a Comment