summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author Shai Barack <shayba@google.com> 2024-01-31 17:42:17 +0000
committer Shai Barack <shayba@google.com> 2024-01-31 17:42:17 +0000
commit6e3dfe61ce9ebf007c91c080fa802a24619b4041 (patch)
tree3809f3b346085fc4b248c58c8f7f20e68cbd7e03
parentc415ebcda9e6275112566c09d4c9d7741d9d6098 (diff)
[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
-rw-r--r--core/java/android/app/QueuedWork.java34
1 files changed, 23 insertions, 11 deletions
diff --git a/core/java/android/app/QueuedWork.java b/core/java/android/app/QueuedWork.java
index edf0a46b1433..6a114f908a22 100644
--- a/core/java/android/app/QueuedWork.java
+++ b/core/java/android/app/QueuedWork.java
@@ -114,6 +114,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}.
*
* Used by SharedPreferences$Editor#startCommit().
@@ -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");
- }
+ if (DEBUG) {
+ 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) {