I want to know how AsyncTask works internally.
I know it uses the Java Executor to perform the operations but still some of the questions I am not understanding. Like:
- How many AsyncTask can be started at a time in an Android app?
- When I start 10 AsyncTask, will all tasks will run simultaneously or one by one?
I have tried with 75000 AsyncTask to test the same. I don’t get any problem and seems like all the tasks will be pushed to stack and will run one by one.
Also when I start 100000 AsyncTasks, I start getting OutOfMemoryError.
So is there any limit of no of AsyncTask which can be run at a time?
Note: I have tested these on SDK 4.0
AsyncTaskhas a rather long story.When it first appeared in Cupcake (1.5) it handled background operations with a single additional thread (one by one). In Donut (1.6) it was changed, so that a pool of thread had begun to be used. And operations could be processed simultaneously until the pool had been exhausted. In such case operations were enqueued.
Since Honeycomb default behavior is switched back to use of a single worker thread (one by one processing). But the new method (executeOnExecutor) is introduced to give you a possibility to run simultaneous tasks if you wish (there two different standard executors:
SERIAL_EXECUTORandTHREAD_POOL_EXECUTOR).The way how tasks are enqueued also depends on what executor you use. In case of a parallel one you are restricted with a limit of 10 (
new LinkedBlockingQueue<Runnable>(10)). In case of a serial one you are not limited (new ArrayDeque<Runnable>()).So the way your tasks are processed depends on how you run them and what SDK version you run them on.
As for thread limits, we are not guaranteed with any, yet looking at the ICS source code we can say that number of threads in the pool can vary in range
5..128.When you start 100000 with default
executemethod serial executor is used.Since tasks that cannot be processed immediately are enqueued you get
OutOfMemoryError(thousands of tasks are added to the array backed queue).Exact number of tasks you can start at once depends on the memory class of the device you are running on and, again, on executor you use.