当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How do I proceed with CompletableFuture without waiting for output

问题描述:

I got a situation where I need to implement a recursion with CompletableFuture. I want to call recursionFuture(ex) whenever any of the CompletableFutures returns any result but I am not sure how do I implement that. In the current situation, recursionFuture(ex) is called only when both future1 and future2 returns output and then if condition is being checked. Any help would be appreciated.

public static void recursionFuture(ExecutorService ex)

{

try

{

CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex);

CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex);

if (future1.get() != null | future2.get() != null)

{

System.out.println("Future1: " + future1.get() + " Future2: " + future2.get());

recursionFuture(ex);

}

}

catch(Exception e)

{

e.printStackTrace();

}

}

网友答案:

You can combine anyOf() with thenRun() to achieve that. Just don't call get() on both futures because it makes your program to wait for the completion. You can use isDone() to check if a future is completed before calling get().

CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex);  
CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex);

CompletableFuture.anyOf(future1, future2).thenRun(() -> {
    if (future1.isDone()) {
        System.out.println("Future 1: " + future1.get());
    }
    if (future2.isDone()) {
        System.out.println("Future 2: " + future2.get());
    }
    recursionFuture(ex);
});

anyOf() will create a new future that will complete as soon as any of the provided futures has completed. thenRun() will execute the given Runnable as soon as the future it's called on is completed.

网友答案:

If you only use two CompletableFutures, you could also have a look at runAfterEither / runAfterEitherAsync. There are also versions which allow to access the value returned like acceptEither / acceptEitherAsync.

分享给朋友:
您可能感兴趣的文章:
随机阅读: