Whaaaaaat Whaaaaaat - 5 months ago 16
Java Question

How do I return a value from two CompletableFutures?

I have a piece of Java code with two

CompletableFuture
s, like so:

CompletableFuture<Boolean> future1 = CompletableFuture.supplyAsync(() ->
doThing1(withThis));

CompletableFuture<Boolean> future2 = CompletableFuture.supplyAsync(() ->
doThing2(withThat));


I want to race these two
CompletableFuture
s and take the first resulting Boolean and store it in a variable. However, I would also like to ensure that neither future runs for longer than 60 seconds (although this is unnecessary). I then want to ensure that both of these
CompletableFuture
s are killed, and my program resumes on just the main thread.

How could I pull this off simply and reliably? Or, am I using the wrong tools for the job at hand?

Answer

You could use CompletableFuture.anyOf(). Call get, and then cancel both of them:

CompletableFuture<Object> future3 = CompletableFuture.anyOf(future1, future2);
Boolean result = (Boolean) futur3.get();
future1.cancel(true);
future2.cancel(true);
return result;
Comments