ASyncTasks blocking others ASyncTasks blocking others multithreading multithreading

ASyncTasks blocking others


This is how I handle this in my code:

if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {    new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);} else {    new MyAsyncTask().execute();}

And replace MyAsyncTask with yours Task1 and Task2 respectively. Basically change in AsyncTask appeared in Honeycomb (see Android SDK docs here in "Order of execution" section), so before that, you launch it as usual, for HC and up, use executeOnExecutor() if you do not like new behaviour (noone does, I think)


A slightly more general way to do this is to put two helper methods in a utility class like so:

class Utils {    @SuppressLint("NewApi")    public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task, P... params) {        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);        } else {            task.execute(params);        }    }}

Then you can execute tasks with Utils.execute(mytask) or Utils.execute(mytask, params) and it will take care of executing them in parallel.


The problem is that every AsyncTask run in the same ThreadPoolExecutor which is coded into the API. This ThreadPoolExecutor can create a different number of WorkerThread depending on your Android version. I don't remember the number versions but the idea is that in older Android versions it was 1 WorkerThread. Then it was updated to 5 in later versions. And recently got moved back to 1 again. This is why your AsyncTasks are blocked. They run all on the same WorkerThread and thus they execute sequentially. Try using executeOnExecutor with THREAD_POOL_EXECUTOR to achieve true parallel execution. However you can use this only since API 11.