The CommonsBlog


AsyncTask Threading Regression Confirmed

A long time ago, Romain Guy indicated that AsyncTask would eventually move to serialized operation, where only one task would execute at a time, rather than the behavior (starting with Android 1.6) of having tasks run in parallel.

While code to this effect appeared in the repo and JavaDocs, I could not reproduce the problem, and so I wasn’t sure what to make of it.

Today, I have been illuminated.

(and, no, I do not mean that I have been decorated by monks in gold leaf, because that would just be creepy)

If your android:targetSdkVersion is set to 13 or higher, and you are running on Android 4.x or higher, AsyncTask will use an Executor that executes only one task at a time. Otherwise, you get the older parallel execution behavior. It is possible that this behavior kicked in on some patchlevel release of 3.2, but current indications are that it did not.

You can opt into having your tasks continue to be executed in parallel by using executeOnExecutor() and AsyncTask.THREAD_POOL_EXECUTOR.

The thread where this analysis was done, including Dianne Hackborn’s rationale for the decision, can be found on the android-developers Google Group.

If you have been making heavy use of AsyncTask, you need to consider how this will be affecting your code, and decide which tasks you want serialized and which you really do want in parallel.

If your build target is set to API Level 11 or higher, and you want to specifically use parallel tasks, you will want to start stating that explicitly in your code, akin to:

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

(if you are still supporting Android 1.x, or if you refuse to set your build target to API Level 11+, the code is commensurately harder)

While this code is not necessary until you set your android:targetSdkVersion to 13 or higher, that sort of change is easy to miss – you might think bumping the target only affects some UI stuff and miss that it seriously affects your threading logic.

Many thanks to Ms. Hackborn for helping to clarify what is going on, and many thanks to Kostya Vasilyev for helping to get to the bottom of this.