Pipeline-specific timeouts with CompletableFuture#orTimeout and JAX-RS 2.1

CompletableFuture#orTimeout (>= Java 9) method

"...exceptionally completes this CompletableFuture with a TimeoutException if not otherwise completed before the given timeout. ..."
and is therefore well suited to set a pipeline-specific timeout.

The method AsyncResponse#setTimeout sets the max timeout per request:

import static java.util.concurrent.CompletableFuture.supplyAsync;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Response;

public class PingResource {

    public void ping(@Suspended AsyncResponse response) {
        response.setTimeout(1, TimeUnit.SECONDS); //global timeout
                orTimeout(100, TimeUnit.MILLISECONDS). //pipeline specific timeout
                exceptionally((t) -> handleTimeout(response::resume, t));

    Void handleTimeout(Consumer<Response> consumer, Throwable t) {
                header("cause", "timeout in the pipeline").
                header("exception", t.toString()).
        return null;

    public String answer() {
        try {
            return "42 + " + System.currentTimeMillis();
        } catch (InterruptedException ex) {
            throw new IllegalStateException("cannot sleep");

The request: curl -i http://localhost:8080/completable-timeout/resources/ping returns:

HTTP/1.1 503 Service Unavailable
X-Powered-By: Servlet/4.0
cause: timeout in the pipeline
exception: java.util.concurrent.TimeoutException

See you at Java EE 8 / Java 9 / Web Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

NEW online workshop: Web Components training (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns


Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments