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 javax.ws.rs.client.AsyncInvoker interface or the submit() methods on javax.ws.rs.client.Invocation. 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.
packagejavax.ws.rs.client;publicinterfaceAsyncInvoker{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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access