Android: Add helper function to synchronously execute Callables on Handler

TBR=hbos

Review URL: https://codereview.webrtc.org/1398283002 .

Cr-Commit-Position: refs/heads/master@{#10246}
This commit is contained in:
Magnus Jedvert 2015-10-12 09:15:45 +02:00
parent 3ba4e28a27
commit e9e3668759

View File

@ -27,6 +27,9 @@
package org.webrtc;
import android.os.Handler;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
final class ThreadUtils {
@ -100,4 +103,27 @@ final class ThreadUtils {
}
});
}
/**
* Post |callable| to |handler| and wait for the result.
*/
public static <V> V invokeUninterruptibly(final Handler handler, final Callable<V> callable) {
class Result {
public V value;
}
final Result result = new Result();
final CountDownLatch barrier = new CountDownLatch(1);
handler.post(new Runnable() {
@Override public void run() {
try {
result.value = callable.call();
} catch (Exception e) {
throw new RuntimeException("Callable threw exception: " + e);
}
barrier.countDown();
}
});
awaitUninterruptibly(barrier);
return result.value;
}
}