Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 6e3dfe61 authored by Shai Barack's avatar Shai Barack
Browse files

[queuedwork] Avoid blocking on thread creation

Never create a HandlerThread just to then see that its queue is empty.
Reduces exposure to priority inversions.

Bug: 263820216

Change-Id: Id8db19b56a690c4eae88386554fa060d40e0b012
parent c415ebcd
Loading
Loading
Loading
Loading
+23 −11
Original line number Diff line number Diff line
@@ -113,6 +113,22 @@ public class QueuedWork {
        }
    }

    /**
     * Remove all Messages from the Handler with the given code.
     *
     * This method intentionally avoids creating the Handler if it doesn't
     * already exist.
     */
    private static void handlerRemoveMessages(int what) {
        synchronized (sLock) {
            if (sHandler == null) {
                // Nothing to remove
                return;
            }
            getHandler().removeMessages(what);
        }
    }

    /**
     * Add a finisher-runnable to wait for {@link #queue asynchronously processed work}.
     *
@@ -156,17 +172,13 @@ public class QueuedWork {
        long startTime = System.currentTimeMillis();
        boolean hadMessages = false;

        Handler handler = getHandler();

        synchronized (sLock) {
            if (handler.hasMessages(QueuedWorkHandler.MSG_RUN)) {
                // Delayed work will be processed at processPendingWork() below
                handler.removeMessages(QueuedWorkHandler.MSG_RUN);

            if (DEBUG) {
                    hadMessages = true;
                    Log.d(LOG_TAG, "waiting");
                hadMessages = getHandler().hasMessages(QueuedWorkHandler.MSG_RUN);
            }
            handlerRemoveMessages(QueuedWorkHandler.MSG_RUN);
            if (DEBUG && hadMessages) {
                Log.d(LOG_TAG, "waiting");
            }

            // We should not delay any work as this might delay the finishers
@@ -257,7 +269,7 @@ public class QueuedWork {
                sWork = new LinkedList<>();

                // Remove all msg-s as all work will be processed now
                getHandler().removeMessages(QueuedWorkHandler.MSG_RUN);
                handlerRemoveMessages(QueuedWorkHandler.MSG_RUN);
            }

            if (work.size() > 0) {