From 633a3aa26fbe9dc40df880ba4ffa7b863f11e473 Mon Sep 17 00:00:00 2001 From: magjed Date: Mon, 16 Nov 2015 05:12:30 -0800 Subject: [PATCH] ThreadUtils: Add joinUninterruptibly() with timeout This is similar to com.google.common.util.concurrent.Uninterruptibles.joinUninterruptibly(). http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/Uninterruptibles.html#joinUninterruptibly(java.lang.Thread,%20long,%20java.util.concurrent.TimeUnit) Review URL: https://codereview.webrtc.org/1444273002 Cr-Commit-Position: refs/heads/master@{#10651} --- .../java/android/org/webrtc/ThreadUtils.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/talk/app/webrtc/java/android/org/webrtc/ThreadUtils.java b/talk/app/webrtc/java/android/org/webrtc/ThreadUtils.java index b078cb8b19..bd4fa44b9a 100644 --- a/talk/app/webrtc/java/android/org/webrtc/ThreadUtils.java +++ b/talk/app/webrtc/java/android/org/webrtc/ThreadUtils.java @@ -88,6 +88,29 @@ final class ThreadUtils { } } + public static boolean joinUninterruptibly(final Thread thread, long timeoutMs) { + final long startTimeMs = SystemClock.elapsedRealtime(); + long timeRemainingMs = timeoutMs; + boolean wasInterrupted = false; + while (timeRemainingMs > 0) { + try { + thread.join(timeRemainingMs); + break; + } catch (InterruptedException e) { + // Someone is asking us to return early at our convenience. We can't cancel this operation, + // but we should preserve the information and pass it along. + wasInterrupted = true; + final long elapsedTimeMs = SystemClock.elapsedRealtime() - startTimeMs; + timeRemainingMs = timeoutMs - elapsedTimeMs; + } + } + // Pass interruption information along. + if (wasInterrupted) { + Thread.currentThread().interrupt(); + } + return !thread.isAlive(); + } + public static void joinUninterruptibly(final Thread thread) { executeUninterruptibly(new BlockingOperation() { @Override