REST timeouts
In this example, we will see how to use the timeouts on the JAX-RS asynchronous methods:
@GET @Path("/withTimeout") publicvoid asyncGetWithTimeout(@Suspendedfinal AsyncResponse asyncResponse) { asyncResponse.setTimeoutHandler(new TimeoutHandler() { @Override publicvoidhandleTimeout(AsyncResponse asyncResponse) { asyncResponse.resume(status(SERVICE_UNAVAILABLE).entity("Operation time out.").build()); } }); asyncResponse.setTimeout(1, SECONDS); new Thread(new Runnable() { @Override publicvoid 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)
method directly to the resource. The setTimeoutHandler()
method represents a handler that will be invoked when timeout is reached so that...