androidmultithreadingandroid-asynctaskthread-priority

Default AsyncTask thread priority (BACKGROUND) is not applied


In default async task constructor source we have following code, which sets thread priority to Process.THREAD_PRIORITY_BACKGROUND = 10

  mWorker = new WorkerRunnable<Params, Result>() {
        public Result call() throws Exception {
            mTaskInvoked.set(true);
            Result result = null;
            try {
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                result = doInBackground(mParams);
                Binder.flushPendingCommands();
            } catch (Throwable tr) {
                mCancelled.set(true);
                throw tr;
            } finally {
                postResult(result);
            }
            return result;
        }
    };

I created a sample application where I created simple asynctask and in doInBackground() I log thread priority via

Log.d("@@@ AsyncTask", "Thread name = " + Thread.currentThread().getName() + "Tread priority " + Thread.currentThread().getPriority());

Expected result: com.example.myapplication D/@@@ AsyncTask: Thread name = AsyncTask #1Tread priority 10

Actual result: com.example.myapplication D/@@@ AsyncTask: Thread name = AsyncTask #1Tread priority 5

Thread priority of background thread is the same as Main thread priority com.example.myapplication D/@@@ MainActivity onCreate: Thread name = mainTread priority 5

I've tested this on API 19 and API 26. Result is the same.

Why background thread priority is not applied in async task? Or my method of reading priority is wrong?

I can upload sources to github, but there not much to upload. Only AsyncTask and log statement.


Solution

  • Turned out that my method of getting thread priority was wrong.

    Right approach for getting thread priority is Process.getThreadPriority(Process.myTid())