Recently I attended an interview in which I was asked a question: How many asynctask can be used in a class? By using execute method you will use by calling asynctask. So maximum limit of asynctask in a class is the question thrown to me.
What is the answer for this? Can someone please explain how many and why?
The question itself does not make any sense. You can use as many
AsyncTask
in a class as you want, if there were a restriction on that it would be ridiculous. I assume he meant how manyAsyncTask
can be executed at the same time and how they are executed and the answer to that would be: It depends.AsyncTasks
can be executed either in series or in parallel. The default behaviour depends on the API level of the device. The documentation ofexecute()
ofAsyncTask
says:Having said that you can choose whether you want to execute them in parallel or in series like this:
However even if you run the tasks in parallel there is a limit to how many can run at the same time. To find out where that limit is you have to look into the source code of AsyncTask.
Up until Android 4.3 (Jelly Bean) the limits were hardcoded to those values:
But with Android 4.4 that was changed and the limits are calculated depending on the used processor in the device:
The implementation of the
ThreadPoolExecutor
remained the same in both cases:So that should pretty much answer your question. But if you really want to find out how the
AsyncTask
works then you should study the source code yourself! This link leads to the AsyncTask implementation on Android 4.4.