Transform Java Future into a CompletableFuture

前端 未结 6 1268
野的像风
野的像风 2020-11-27 15:43

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,

6条回答
  •  余生分开走
    2020-11-27 16:00

    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.

提交回复
热议问题