In this example, we will see how to use the timeouts on the JAX-RS asynchronous methods:
@GET
@Path("/withTimeout")
public void asyncGetWithTimeout(@Suspended final AsyncResponse asyncResponse) {
asyncResponse.setTimeoutHandler(new TimeoutHandler() {
@Override
public void handleTimeout(AsyncResponse asyncResponse) {
asyncResponse.resume(status(SERVICE_UNAVAILABLE).entity("Operation time out.").build());
}
});
asyncResponse.setTimeout(1, SECONDS);
new Thread(new Runnable() {
@Override
public void run() {
String result = ...
asyncResponse.resume(result);
}
}).start();
}
Timeouts are not defined by default on the suspended resource instance; so, we risk endless expectations in some cases. We can use the setTimeoutHandler method to configure a timeout event handler and the setTimeout(Long, TimeUnit...