Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: AsyncTask OR normal Java threads with ExecutorService [closed]

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:

  1. AsyncTask:

    Pros:

    • easy to use
    • android specific
    • easy UI-interaction

    Cons:

    • Since I have to use API level 10, there is no ExecutorService with fixed thread pool to execute the AsyncTasks
  2. Normal Java Threads:

    Pros:

    • ExecutorService with fixed thread pool

    Cons:

    • Not so easy to handle, e.g. UI-interaction

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?

like image 986
Tobias Avatar asked Jul 02 '11 14:07

Tobias


People also ask

Does ExecutorService shutdown automatically?

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.

How do I stop the ExecutorService thread?

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.

How do I shut down ExecutorService gracefully?

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.

What happens to AsyncTask if activity is destroyed?

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.


1 Answers

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.

like image 198
CommonsWare Avatar answered Sep 30 '22 21:09

CommonsWare