JAX-RS - Asynchronous Client

[Updated: Aug 24, 2017, Created: Aug 24, 2017]

The JAX-RS client API supports asynchronous request processing. By default, invocations are synchronous but can be set to run asynchronously by calling the Invocation.Builder.async() method and registering an instance of InvocationCallback.

Example

A resource with async processing

@Path("/orders")
public class OrderResource {

  @GET
  public void getAllOrders(@Suspended final AsyncResponse ar) {
      ExecutorService es = Executors.newSingleThreadExecutor();
      es.submit(() -> {
          try {
              //Simulating a long running process
              Thread.sleep(2000);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
          ar.resume("all orders data....");
          es.shutdown();
      });
  }
}

The resource client with async callback

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();
      target.request().async().get(new InvocationCallback<Response>() {
          @Override
          public void completed(Response response) {
              String responseString = response.readEntity(String.class);
              System.out.println("response: " + responseString);
              System.out.println("time taken: " + (System.currentTimeMillis() - start));
          }

          @Override
          public void failed(Throwable throwable) {
              throwable.printStackTrace();
          }
      });
      System.out.println("request returns");
  }
}

Output

request returns
response: all orders data....
time taken: 2359

Note that, in above example (as compare to this example), the main method exits before getting the response.

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

JAX-RS Asynchronous Client Example Select All Download
  • jaxrs-asynchronous-client
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also