Asynchronous JAX-RS: Timeout Configuration and Handling

Asynchronous JAX-RS request can be configured with a timeout, as well as, custom timeout handling:


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

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;

@Path("ping")
public class PingResource {

    @GET
    public void ping(@Suspended AsyncResponse response) {
        response.setTimeout(1, TimeUnit.SECONDS);
        response.setTimeoutHandler(this::onTimeout);
        //managed thread pools omitted
        CompletableFuture.supplyAsync(this::heavyThinking).thenAccept(response::resume);
    }

    String heavyThinking() {
        try {
            Thread.sleep(1000 * 2);
        } catch (InterruptedException e) {}
        return "42";
    }

    public void onTimeout(AsyncResponse response) {
        response.resume(Response.status(204).header("info", "late, but o.k").build());
    }

}

CLI: curl -i http://localhost:8080/jaxrs-async-timeout/resources/ping yields:


HTTP/1.1 204 No Content
Server: Payara Server  5.191 #badassfish
info: late, but o.k    

Project created with javaee8-essentials-archetype, the 4kB ThinWAR was built and deployed with: wad.sh in 2.4s

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


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

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