In a recent post, I had stated that AsyncTask creates a new thread every time a task is executed. Well, that’s not true. Starting with Android 1.6 Donut, a pool of threads is used. An answer in StackOverflow provides more insight. I have verified most of what is stated there. System can create up to 128 threads. However, only a maximum of 5 threads are kept alive in the pool. Extra threads (beyond 5) are immediately killed after termination of the AsyncTask.
I also found out that calling AsyncTask.cancel(true) has no impact on the pool size. That is, it doesn’t actually kill the thread. Only threads that are killed are the ones beyond the 5 that are kept in the pool.
In summary, because a pool is used, AsyncTask may be used to performs short tasks repeatedly. Unless you are queuing more than 5 tasks at the same time, no new thread will be created. If, however, the number of concurrent tasks exceeds 5, it may be better to use ExecutorService as I said in my post.
That leaves one unanswered question. The relevant section of AsyncTask documentation says:
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.
I am puzzled by the last bit about Honeycomb. What does it mean by “tasks are executed on a single thread?” From my tests done in Ice Cream Sandwich, clearly, each task runs in its own separate thread. If you have any idea about what the documentation is saying, please leave a comment here.