Jinggang
Jinggang

Reputation: 431

Java CompletableFuture, when is completableFuture.handle called?

Q1. My understanding is completableFuture.handle is called if the future is completed either normally or exceptionally. But what about a timeout scenario?

Q2. Where to check the default timeout setting of a completableFuture? How to change it? What happens after a future timeout? (completion or exception ?)

Q3. I need to doSomething() as long as a future is "done"(completed or timeout or whatever final stage). Is there a method that is guaranteed to be called after the future is "done"? Where should I put doSomething()?

New to completable future. Prefer answers with Java 8. Thanks for your help.

Upvotes: 1

Views: 1415

Answers (1)

Holger
Holger

Reputation: 298233

There is no timeout feature in CompletableFuture before Java 9. However, your questions still can be answered due to the way CompletableFuture works fundamentally.

There are only two ways to complete a CompletableFuture, normally (with a value) or exceptionally (with a Throwable). So any completion that does not provide a result value must be done exceptionally, providing a throwable.

So cancellation works by completing the future exceptionally with a CancellationException. And starting with Java 9, a timeout will work by completing the future exceptionally with a TimeoutException.

This implies that any stage that is guaranteed to be executed on completion in either case, when completed normally or exceptionally, like chained with handle or whenComplete, will always get executed, whether the prerequisite stage failed with an exception, has been canceled or a timeout elapsed. You will have to inspect the provided throwable to find out which of these scenarios happened.

Since the TimeoutException already exists in Java 8, you can already implement special handling for it. You can even implement a compatible trigger for it, e.g. by scheduling an action to a ScheduledExecutorService which will call completeExceptionally​(new TimeoutException()) on your future after an elapsed time (keep in mind that this will be ignored when the future is already completed). That’s not much different to how Java 9’s builtin timeout does it.

To address the last open point, even in future versions, there is no default timeout setting. There will be only a timeout, if you request it explicitly (providing your intended timeout value).

Upvotes: 2

Related Questions