CompletableFuture and async composition question 99 of 180 mid
How do you add a timeout to a CompletableFuture?
get(timeout)is the only option and it is fine- Correct:
orTimeout(n, unit)fails the future,completeOnTimeout(value, n, unit)supplies a fallback, both without blocking a thread Thread.sleepin awhenComplete- Timeouts are not supported
get(timeout, unit) bounds how long you wait, but it blocks a thread to do it and leaves the task
running. Since Java 9 there are two non-blocking alternatives:
fetchPrice()
.completeOnTimeout(Price.UNKNOWN, 200, MILLISECONDS) // fall back
.orTimeout(1, SECONDS); // or fail hard
Both are scheduled on an internal single-threaded timer, so they cost no thread while waiting. Remember the previous question: the timeout completes the future, it does not stop the underlying call, so a slow downstream request still occupies its connection until it finishes.
Quiz yourself on CompletableFuture and async composition Suggest a correction