By default injecting AsyncResponse via @Suspended (last example), suspends the processing indefinitely (till we call AsyncResponse#resume()). The suspend timeout as well as a custom timeout handler can be specified using the AsyncResponse.setTimeout(long, TimeUnit) and AsyncResponse.setTimeoutHandler(TimeoutHandler) methods.
Example
A async resource method with timeout handling
@Path("/orders")
public class OrderResource {
@GET
public void getAllOrders(@Suspended final AsyncResponse ar) {
ExecutorService es = Executors.newSingleThreadExecutor();
ar.setTimeoutHandler(new TimeoutHandler() {
@Override
public void handleTimeout(AsyncResponse asyncResponse) {
asyncResponse.resume("Processing timeout.");
es.shutdown();
}
});
ar.setTimeout(2, TimeUnit.SECONDS);
es.submit(() -> {
try {
//Simulating a long running process
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ar.resume("all orders data....");
es.shutdown();
});
}
}
response: Processing timeout. time taken: 2549 request returns
Note
If the timeout value is reached and no timeout handler is registered, JAX-RS server side generates a ServiceUnavailableException with the status set to 503.
Example Project
Dependencies and Technologies Used:
jersey-server 2.25.1: Jersey core server implementation.
jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.