Java Concurrency Interview

CompletableFuture and async composition question 99 of 180 mid

How do you add a timeout to a CompletableFuture?

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.

completablefuture api

Quiz yourself on CompletableFuture and async composition Suggest a correction