I have a utility method (used for unit testing, it so happens) that executes a Runnable
in another thread. It starts the thread running, but does not wait for the Thread
to finish, instead relying on a Future
. A caller of the method is expected to get()
that Future
. But is that enough to ensure safe publication of the computation done by the Runnable
?
Here is the method:
private static Future<Void> runInOtherThread(final CountDownLatch ready, final Runnable operation) {
final CompletableFuture<Void> future = new CompletableFuture<Void>();
final Thread thread = new Thread(() -> {
try {
ready.await();
operation.run();
} catch (Throwable e) {
future.completeExceptionally(e);
return;
}
future.complete(null);
});
thread.start();
return future;
}
After calling Future.get()
on the returned Future
, can the caller of the method safely assume that the Runnable
has finished execution, and its results have been safely published?
Future#get
blocks until the operation completes (or fails) that I would suggest yes - but I might be missing something in the question – Manque