Close

JAX-RS - Asynchronous Processing with Timeout Handler

[Last Updated: Aug 24, 2017]

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();
      });
  }
}

The resource client

public class OrderClient {
  public static void main(String[] args) throws Exception {
      Client client = ClientBuilder.newBuilder().build();
      WebTarget target =
              client.target("http://localhost:8080/orders");
      long start = System.currentTimeMillis();
      Response response = target.request().get(Response.class);
      String responseString = response.readEntity(String.class);
      System.out.println("response: " + responseString);
      System.out.println("time taken: " + (System.currentTimeMillis() - start));
      System.out.println("request returns");
  }
}

Output

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.
  • JDK 1.8
  • Maven 3.3.9

Asynchronous Processing with Timeout Example Select All Download
  • jaxrs-async-processing-with-timeout
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • OrderResource.java

    See Also