My application uses a Service
to do some background stuff. I am using additional threads in the service to do some computation. For this purpose I create two threads every 5 to 10 seconds, which are running 5 to 10 seconds. But I don't know which thread-model I should use:
AsyncTask:
Pros:
Cons:
ExecutorService
with fixed thread pool to execute the AsyncTasksNormal Java Threads:
Pros:
Cons:
Which model is better to use? Especially in concern of performance. Is there a heavy overhead when i am using AsyncTasks, and is the ExecutorService faster in reusing the threads than Android in creating new AsyncTasks?
Using shutdown() and awaitTermination() In general, the ExecutorService will not be automatically destroyed when there is no task to process. It will stay alive and wait for new tasks to come.
To properly shut down an ExecutorService, we have the shutdown() and shutdownNow() APIs. The shutdown() method doesn't cause immediate destruction of the ExecutorService. It will make the ExecutorService stop accepting new tasks and shut down after all running threads finish their current work: executorService.
Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks.
If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.
If you look at the implementation of AsyncTask
, you will see that it uses its own thread pool using "normal Java threads".
Is there a heavy overhead when i am using AsyncTasks, and is the ExecutorService faster in reusing the threads than Android in creating new AsyncTasks?
There should be no substantial difference between the two.
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