Asynchronous resources
The following example shows a simple asynchronous resource method using the new JAX-RS async features:
@GET @Path("/simple") publicvoid asyncGet(@SuspendedfinalAsyncResponseasyncResponse) { new Thread(new Runnable() { @Override publicvoid run() { String result = veryExpensiveOperation(); asyncResponse.resume(result); } private String veryExpensiveOperation() { returnnew MagicNumber(3) + ""; } }).start(); }
We have a JAX-RS AsyncResponse
class passed as an attribute to a GET method implementation, asyncGet
. This method injects an instance of AsyncResponse
using the javax.ws.rs.container.Suspended
annotation.
This annotation is very similar to the javax.ws.rs.core.Context
annotation. The @Context
annotation allows us to inject a REST response. The @Suspend
annotation does the same with the difference, it declares the resource as part of an asynchronous operation too.
Asynchronous is when a thread is different when starting the thread end operation....