Question

There are two ways to execute AsynTask, i.e., execute and executeOnExecutor. I already know that execute works serially and executeOnExecutor works in parallel. So my question is:

  • Which one to use?
  • Which one is better?
  • Can someone help me understand which one to use in which situation?
Was it helpful?

Solution

On recent versions of android, "execute" will cause your task to be put into a queue from which a single background thread will pick it up and execute it; as you say, such tasks are executed serially (although you should not rely on this, as older versions of android started one thread for each task).

executeOnExecutor, however, gives you more control, because you can use any object that implements the Executor interface to execute the task. Even if you only limit yourself to the standard ThreadPoolExecutor implementation, this means you can take control of:

  • the maximum number of tasks that can be executed simultaneously
  • the type and parameters of queue used (e.g. whether the queue is bounded or unbounded)
  • the behavior when a new task is submitted while the queue is full

For most purposes, execute is adequate, but you would use executeOnExecutor when you need more control, either because a single thread isn't enough, or because you need to guarantee you only get one thread when using older versions of android, or because you have an unusual requirement on how submitted tasks are handled.

Licensed under: CC-BY-SA with attribution
scroll top