Asynchronous processing
You can use the asynchronous processing technique in JAX-RS 2.0 to process threads. Asynchronous processing is supported both in the Client API and in the Server API. For more information about asynchronous processing in Client and Server APIs, see Chapter 8 of JSR 339: JAX-RS 2.0: The Java API for RESTful Web Services (the "Specification").
The following two examples show asynchronous processing in the Client and Server
APIs:
- Asynchronous processing in the Client
API:
Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://example.org/customers/{id}"); target.resolveTemplate("id", 123).request().async().get( new InvocationCallbackCustomer() { @Override public void completed(Customer customer) { // Do something } @Override public void failed(Throwable throwable) { // Process error } });
- Asynchronous processing in the Server
API:
@Path("/async") public class MyResource{ @GET public void getAsync(@Suspended final AsyncResponse asyncResponse){ CompletionCallback callBack = new CompletionCallback(){ @Override public void onComplete(Throwable throwable) { ... } }; asyncResponse.register(callBack); asyncResponse.resume("some Response"); } }
The JAX-RS 2.0 implementation in Liberty supports EJB and the use of stateless and
singleton session beans as root resource classes. When an EJB method is annotated
with @Asynchronous, the EJB container automatically allocates the
necessary resources for its execution. Thus, in this scenario, it is unnecessary to
use an Executor to generate an asynchronous response. For example,
@Stateless
@Path("/")
class EJBResource {
@GET @Asynchronous
public void longRunningOp(@Suspended AsyncResponse ar) {
executeLongRunningOp();
ar.resume("Hello async world!");
}
}
Explicit
thread management is not needed in this case because that is under the control of
the EJB container. The response is produced by calling resume on the injected
AsyncResponse. Hence, the return type of
longRunningOp is void.