diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionService.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionService.java index 2f314cb730422c..fd11cf0c2c13ea 100644 --- a/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionService.java +++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionService.java @@ -1596,8 +1596,6 @@ public void shutdown() { } if (remoteCache != null) { - remoteCache.release(); - try { backgroundTaskPhaser.awaitAdvanceInterruptibly(backgroundTaskPhaser.arrive()); } catch (InterruptedException e) { @@ -1605,6 +1603,12 @@ public void shutdown() { remoteCache.shutdownNow(); Thread.currentThread().interrupt(); } + + // Only release the remoteCache once all background tasks have been finished. Otherwise, the + // last task might try to close the remoteCache inside the callback of network response which + // might cause deadlocks. + // See https://github.com/bazelbuild/bazel/issues/21568. + remoteCache.release(); } if (remoteExecutor != null) {