Simultaneous HttpClient request using multiple AsyncTasks Simultaneous HttpClient request using multiple AsyncTasks multithreading multithreading

Simultaneous HttpClient request using multiple AsyncTasks


It is because AsyncTask management changed in Honeycomb . Previously if you started i.e. 3 AsyncTasks, these were running simultaneously. Since HC, if your targetSdk is set to 12 or higher, these are queued and executed one by one (see this discussion). To work that around start your AsyncTasks that way:

task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);

instead of:

task.execute(params);

If you target also older Androids, you need conditional code:

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

or wrap it in a separate helper class:

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

and usage would be i.e.:

Utils.executeAsyncTask( new MyAsyncTask() );


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. Source

So depending on the version AsyncTask would not execute in parallel. For tasks like file download you should use thread pool using Executor

or you can use executeOnExecutor method..


It seems that you share an instance of HttpClient across your application and give your AsyncTasks their own methods. By the by, I'm fully aware that the link is for the older version, but the document doesn't seem to be updated for 4.x.