Chapter 13. Asynchronous JAX-RS

Another interesting new feature introduced in JAX-RS 2.0 is asynchronous request and response processing both on the client and server side. If you are mashing together a lot of data from different websites or you have something like a stock quote application that needs to push events to hundreds or thousands of idle blocking clients, then the JAX-RS 2.0 asynchronous APIs are worth looking into.

AsyncInvoker Client API

The client asynchronous API allows you to spin off a bunch of HTTP requests in the background and then either poll for a response, or register a callback that is invoked when the HTTP response is available. To invoke an HTTP request asynchronously on the client, you interact with the interface or the submit() methods on First, let’s take a look at polling HTTP requests that are run in the background.

Using Futures

The AsyncInvoker interface has a bunch of methods that invoke HTTP requests asynchronously and that return a java.util.concurrent.Future instance. You can use the AsyncInvoker methods by invoking the async() method on the Invocation.Builder interface.


public interface AsyncInvoker {
    Future<Response> get();
    <T> Future<T> get(Class<T> responseType);

    Future<Response> put(Entity<?> entity);
    <T> Future<T> put(Entity<?> entity, Class<T> responseType);

    Future<Response> post(Entity<?> entity);
    <T> Future<T> post(Entity<?> entity, Class<T> responseType ...

Get RESTful Java with JAX-RS 2.0, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.