Video in progress
How do timeouts and cancellation work in CompletableFuture, and what resource leaks can they cause?
orTimeout and completeOnTimeout only complete the future, and the work behind it doesn't stop. cancel(true) doesn't interrupt the running thread either. So real cancellation comes from passing the timeout to the lower layer (the HTTP client, JDBC) or from making the work stoppable by yourself.
📖 Answer
Many teams write code like this and think the timeout solved the problem:
CompletableFuture.supplyAsync(() -> slowClient.fetch(id), ioPool)
.orTimeout(500, TimeUnit.MILLISECONDS)
.exceptionally(ex -> Fallback.EMPTY);
The user gets a response at 500 ms, but slowClient.fetch keeps running on an ioPool thread for 30 seconds. Under load the pool fills up, and later requests slow down too. The timeout hid the symptom, and the resource stayed busy.
The cause is that a CompletableFuture isn't tied to the thread that runs the computation. Its cancel(mayInterruptIfRunning) parameter has no effect, according to the Javadoc: the future ends with a CancellationException, that's all. Cancellation doesn't propagate to earlier stages in the chain either.
The right approaches:
- Give the timeout to the source.
HttpRequest.timeout(...)inHttpClient,setQueryTimeoutin JDBC,connectionTimeoutin Hikari. Then the lower layer releases the resource itself. - An async client. In newer JDKs, cancelling the future returned by
httpClient.sendAsync(...)tries to abort the request itself, while wrapping a blocking call doesn't. - FutureTask/ExecutorService. If you need an interrupt,
Future.cancel(true)returned byexecutor.submitinterrupts the thread, provided the code responds to interrupts. - Deadline propagation. A deadline is set when the request enters, and each layer computes the time remaining and passes it to the calls below (in gRPC this is standard).
Another hidden leak: futures that nobody joins and whose errors are never caught. They leave no trace in the log. At the system level I add the rule "every async chain ends with a step that handles timeout and error" to the code review checklist, and I put executor active/queue metrics into alerts.
Sign up to mark studied questions and save your progress.