Merge "Optimization when looking up requests for release" am: 0cb136a9c5 am: 86059bafb6 am: 0e5188da24

Original change: https://android-review.googlesource.com/c/platform/frameworks/base/+/1592999

MUST ONLY BE SUBMITTED BY AUTOMERGER

Change-Id: Iadf0132dd7110cab73be750a42105ba99074d2b2
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 154e183..5077cc6 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -3721,7 +3721,12 @@
         // Looking up the app passed param request in mRequests isn't possible since it may return
         // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
         // do the lookup since that will also find per-app default managed requests.
-        final NetworkRequestInfo nri = getNriForAppRequest(request);
+        // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
+        // to avoid potential race conditions when validating a package->uid mapping when sending
+        // the callback on the very low-chance that an application shuts down prior to the callback
+        // being sent.
+        final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
+                ? mNetworkRequests.get(request) : getNriForAppRequest(request);
 
         if (nri != null) {
             if (Process.SYSTEM_UID != callingUid && Process.NETWORK_STACK_UID != callingUid