Java 8 introduces CompletableFuture
, a new implementation of Future that is composable (includes a bunch of thenXxx methods). I\'d like to use this exclusively,
If your Future
is the result of a call to an ExecutorService method (e.g. submit()
), the easiest would be to use the CompletableFuture.runAsync(Runnable, Executor) method instead.
From
Runnbale myTask = ... ;
Future> future = myExecutor.submit(myTask);
to
Runnbale myTask = ... ;
CompletableFuture> future = CompletableFuture.runAsync(myTask, myExecutor);
The CompletableFuture
is then created "natively".
EDIT: Pursuing comments by @SamMefford corrected by @MartinAndersson, if you want to pass a Callable
, you need to call supplyAsync(), converting the Callable
into a Supplier
, e.g. with:
CompletableFuture.supplyAsync(() -> {
try { return myCallable.call(); }
catch (Exception ex) { throw new RuntimeException(ex); } // Or return default value
}, myExecutor);
Because T Callable.call() throws Exception;
throws an exception and T Supplier.get();
doesn't, you have to catch the exception so prototypes are compatible.