简体   繁体   中英

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 CompletableFuture s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM