6

Is there a way to elevate the priority of an AsyncTask?

I'm doing some image manipulation in an AsyncTask. On a very slow device, it takes up to 60 seconds to process an image. Now I'd like to increase the performance by elevating the priority of the task. Can it be done somehow?

SePröbläm
  • 5,142
  • 6
  • 31
  • 45

3 Answers3

13

Try to use following (increase of priority AsyncTask threads):

protected final MyResult doInBackground(MyInput... myInput) {
    Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND + THREAD_PRIORITY_MORE_FAVORABLE);
    // blah-blah
}
Barmaley
  • 16,638
  • 18
  • 73
  • 146
8

If you do not have a heavy UI which would interleave with the AsyncTask flow of execution, then your problem is in the algorithm used.

If you can divide your algorithm in parallel tasks, then you can use a pool of executors. If not, your Async Task is just doing serial work.

Be aware that according to AsyncTask:

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR

You can use code like this on most devices

if (Build.VERSION.SDK_INT >= 11) {
    asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
    asyncTask.execute();
}

or even create a custom ThreadPoolExecutor.

Community
  • 1
  • 1
Radu Ionescu
  • 3,462
  • 5
  • 24
  • 43
  • it doesn't change thread priority!! though it helps to run `doInBackground` method faster, for changing Thread priority see the accepted answer... so `executeOnExecutor` is only for fixing delay before thread starts https://stackoverflow.com/questions/12404668/asynctasks-doinbackground-starts-its-execution-too-late-after-asynctaskexecut – user25 May 26 '18 at 21:29
2

Set thread priority inside your AsyncTask doInBackground:

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

Like following:

protected Object doInBackground(Integer... params) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    ...
    ...
}
Jonas Borggren
  • 2,591
  • 1
  • 22
  • 40