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}
This commit is contained in:
magjed
2015-11-16 05:12:30 -08:00
committed by Commit bot
parent e155ae671c
commit 633a3aa26f

View File

@ -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