Pankaj Kumar Katiyar
Pankaj Kumar Katiyar

Reputation: 1494

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();
        }
    }

Upvotes: 0

Views: 3093

Answers (2)

user140547
user140547

Reputation: 8200

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.

Upvotes: 0

Andrew Lygin
Andrew Lygin

Reputation: 6197

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.

Upvotes: 1

Related Questions