Whaaaaaat Whaaaaaat - 1 year ago 73
Java Question

How do I return a value from two CompletableFutures?

I have a piece of Java code with two

s, like so:

CompletableFuture<Boolean> future1 = CompletableFuture.supplyAsync(() ->

CompletableFuture<Boolean> future2 = CompletableFuture.supplyAsync(() ->

I want to race these two
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
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 Source

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();
return result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download