yorkw yorkw - 14 days ago 6
Java Question

AsyncTask.executeOnExecutor() before API Level 11

The normal way we do AsyncTask in Android is, from Android API:

private class DoIntenseTask extends AsyncTask<Object, Object, Void> {
protected Void doInBackground(Object... params) {
for (Object param : params) {
Object rtnObj = doIntenseJob(param);
publishProgress(rtnObj);
}
return null;
}

protected void onProgressUpdate(Object... progress) {
for (Object rtnObj : progress) {
updateActivityUI(rtnObj);
}
}

}


My intense tasks are loosely coupled and the execution order does not matter, by doing this way, a single thread is allocated to run a list of intense tasks. personally I think this is a sort of halfway solution. Yes, the intense job is not running in UI thread anymore, but still need execute one by one (in many cases, we are facing a list of intense job, I think this is also why the methods in AsyncTask are multi-parameterized). Google should make the API more reusable to solve different kind of scenario.

What I really like to have is run a number of doIntenseJob() in parallel managed by a threadpool (e.g. poolSize = 5). Looks like google do give a solution by AsyncTask.executeOnExecutor() but unfortunately only available since API level 11. I am developing app on mobile and wonder if there is a workaround that I can achieve the same behavior under API level 11.

Thanks in advance

Y

Answer

My intense tasks are loosely coupled and the execution order does not matter, by doing this way, a single thread is allocated to run a list of intense tasks.

AsyncTask presently uses a thread pool with several threads. In the future, it may be restricted to a single thread -- Google has hinted that this will be the case.

wonder if there is a workaround that I can achieve the same behavior under API level 11.

The default behavior is the behavior you want. If you examine the source code to AsyncTask, you will see that as of Gingerbread, it used a thread pool with a minimum of 5 threads and a maximum of 128.

Now, bear in mind that the vast majority of Android devices in use today are single-core. Hence, unless your "intense tasks" are intensely not doing much but blocking on network I/O, you do not want to be doing them in parallel, as context switches between threads will simply slow you down further.