AsyncTask vs HandlerThread


If you are developing an app somewhat like photogallery that communicates with a web site to obtain lists (xml api), then again to obtain more detail about each list item, would it be prudent to put ALL the network activity on a background thread as this chapter does for the thumbnails instead of doing the first list fetch on an AsyncTask that is created and torn down everytime there is a list request or additional page request for the list?

Just considering my app structure going forward. Given that pages of data will be forthcoming to the list wouldn’t utilizing the background thread as used for the thumbnails be more appropriate for a scaled up app for processing the list queries?

Thanks in advance.


Hi, TheKog,

I’m not sure if this comment comes too late, but anyway, as far as I know, your decision about using an AsyncTask or HandlerThread must be based on the time your task would take to accomplish its objective. AsyncTasks doesn’t run in its own threads, they actually share the same unique background thread and they’re executed one after the other. If there’s some AsyncTask which takes too much time to finish you can get a starvation issue. In this case, you must use HandlerThreads. On the other hand, AsyncTasks are much more easier to handle and to setup, so, if you got a small task, that will not take too much time to finish, go for it!



Ah I didnt realize a bad AsyncTask could impact others - this is definitely something to avoid. I will likely change to using an executorpool as follows:

@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11 void startMyTask(AsyncTask asyncTask) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); else asyncTask.execute(params); }

The nice thing about asynctask is the callbacks structure, but I guess they simplified the multitasking model because NOOBS didn’t know how to handle true concurrent operations etc. With the executorpool both are readily available - this is definitely something worth pointing out in the next edition…