Search code examples
javafuturecompletable-future

How to wait for a satisfying result from a list of futures?


In java I have a list of futures that can return a result or null. How to wait for whichever completes first and if it returns a result then ignore the rest but if it returns null wait for another one to finish?


Solution

  • Add a completion handler to each future in your list to complete an auxiliary future:

    List<CompletableFuture<String>> futures = ...
        
    var firstNonNull = new CompletableFuture<String>();
    futures.forEach(future -> future.whenComplete( (value, failure) -> {
        if (value != null) {
            firstNonNull.complete(value);
        }
    }));
    
    firstNonNull.whenComplete(...)
    

    Now firstNonNull completes once the first future in futures completes with a non null value.