In the internal implementation of AsyncTask(in Android SDK) here, sDefaultExecutor
is declared with volatile
keyword and also execute()
method in SerialExecutor
is declared with synchronized
keyword.
AsyncTask
, we can't execute the same
instance again unless the previous instance has finished executing.
So how come there can be cases of multiple threads here?SerialExecutor
has an ArrayDeque
? Because at a time we
can have only one task. If we create a new instance of AsyncTask
,
then wont we get a new instance of ArrayDeque
,again which has only
one Task to deal with?ThreadPoolExecutor
. Why are the thread pools
required when for a particular instance of AsyncTask
,we can have
only one Task? One thread is suffice for that.we cant excute the same instance again unless the previous instance has finished executing. So how come there can be cases of multiple threads here?
There is the main UI thread and executor thread(s), for example.
Why the SerialExecutor has an ArrayDeque? Because at a time we can have only one task. If we create a new instance of AsyncTask, then wont we get a new instance of ArrayDeque,again which has only one Task to deal with?
Not true that there can be only one task. The serial executor can execute only one task at a time, but you can queue up more than one task in the main thread and they get executed one by one in the executor thread.
There are other executors than the serial executor, too, like the thread pool executor you mention later.
Same is the case with ThreadPoolExecutor. Why are the thread pools required when for a particular instance of AsyncTask,we can have only one Task? One thread is suffice for that.
Your premise of only one task at a time is not correct. The thread pool executor is useful for running multiple async tasks at the same time in separate threads.
How does queuing of taks and multiple tasks come into picture? Suppose i make an instance of AsyncTask and execute it 5 times. Then if one is running, other 4 wont start. SO how can i get multiple tasks in any case?
You can execute one instance of an AsyncTask
only once. But you can post multiple different instances of AsyncTask
for execution. Note that such posting operation (execute()
and so on) is asynchronous and returns before the async task finishes, and you're able to run additional code in the UI thread, including posting new async tasks for execution.
For parallel execution, just use executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ...)
.
Is it also true that since SerialExecutor is static, so only one instance of it will be used across all the AsyncTask instances and so a queue is required?
Yes, there's only one serial executor in your app and it's shared between all async tasks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With