Java Reference
In-Depth Information
Chapter 13. Asynchronous JAX-RS
Another interesting new feature introduced in JAX-RS 2.0 is asynchronous request and re-
sponse 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 asyn-
chronous APIs are worth looking into.
AsyncInvoker Client API
The client asynchronous API allows you to spin off a bunch of HTTP requests in the back-
ground 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 asynchron-
ously and that return a
java.util.concurrent.Future
instance. You can use the
AsyncIn-
voker
methods by invoking the
async()
method on the
Invocation.Builder
interface.
package
package
javax
.
ws
.
rs
.
client
;
public
public interface
AsyncInvoker
{
Future
<
Response
>
get
();
<
T
>
Future
<
T
>
get
(
Class
<
T
>
responseType
);
interface
AsyncInvoker
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
);
Future
<
Response
>
delete
(
Entity
<?>
entity
);
<
T
>
Future
<
T
>
delete
(
Entity
<?>
entity
,
Class
<
T
>
responseType
);
...
}