Transform Java Future into a CompletableFuture

前端 未结 6 1266
野的像风
野的像风 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:08

    Let me suggest another (hopefully, better) option: https://github.com/vsilaev/java-async-await/tree/master/com.farata.lang.async.examples/src/main/java/com/farata/concurrent

    Briefly, the idea is the following:

    1. Introduce CompletableTask interface -- the union of the CompletionStage + RunnableFuture
    2. Warp ExecutorService to return CompletableTask from submit(...) methods (instead of Future)
    3. Done, we have runnable AND composable Futures.

    Implementation uses an alternative CompletionStage implementation (pay attention, CompletionStage rather than CompletableFuture):

    Usage:

    J8ExecutorService exec = J8Executors.newCachedThreadPool();
    CompletionStage = exec
       .submit( someCallableA )
       .thenCombineAsync( exec.submit(someCallableB), (a, b) -> a + " " + b)
       .thenCombine( exec.submit(someCallableC), (ab, b) -> ab + " " + c); 
    

提交回复
热议问题