rashad.z rashad.z - 1 month ago 18
Android Question

AsyncTask execute() or executeOnExecutor()?

What's the difference between using

execute()
and
executeOnExecuter()
?


  • How does
    execute()
    execute tasks by default? (in serial or in parallel?)

  • What should be used for new SDKs >16?

  • Is it a good practice to use parallel execution (
    THREAD_POOL_EXECUTOR
    ) for tasks rather than serial even if it doesn't matter for the application or does that depends on the number of
    AsyncTask
    s that will be executed?


Answer

How does .execute execute tasks by default (in serial or in parallel).

Before API level 11: parallel.

API level 11 and up: serial.

which should be used for new SDKs >16 (executeOnExecuter ?)

Depends on your requirements. Use execute() if you're happy with the default executor. Use an explicit executor if you're not.

Is it a good practice to use parallel execution (THREAD_POOL_EXECUTOR) for tasks rather than serial even if it doesn't matter for the application or does that depends on the number of async tasks that will be executed?

Async tasks should only be used for relative short backround operations. Quoting AsyncTask documentation:

AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

While the async task is running, the executor thread cannot execute other tasks. On a serial executor with only one executor thread it is easier to detect problems when your tasks run for too long. On a parallel executor detecting such problems takes more simultaneous long-running tasks.

Therefore, if you really need to switch to a parallel executor, you're probably better off revisiting your design.