I want to make parallel calls to different external services and proceed with the first successful response.
Successful here means that the result returned by the service has certain values in certain fields.
However, for CompletableFuture
, everything other than an exception is success. So, even for for business failures, I have to throw an exception to signal non-success to CompletableFuture
. This feels wrong, ideally I would want to provide a boolean to indicate business success/failure. Is there a better way to signal business failures?
The second question I have is, how do I make sure I don't run out of threads due to the abandoned CompletableFuture
s that would keep running even after CompletableFutures.anyOf()
returns. Ideally I want to force stop the threads but as per the thread below, the best I can do is cancel the downstream operations.
How to cancel Java 8 completable future?
When you call CompletableFuture#cancel, you only stop the downstream part of the chain. Upstream part, i. e. something that will eventually call complete(...) or completeExceptionally(...), doesn't get any signal that the result is no more needed.
I can force stop treads by providing my own ExecutorService
and calling shutdown()
/shutdownNow()
on it after CompletableFuture.anyOf()
returns.
However I am not sure about the implications of creating a new ExecutorService instance for each request.