1.

Is it possible to make asynchronous requests in JAX-RS?

Answer»

Yes. the JAX-RS Client API provides a method called Invocation.Builder.ASYNC() that is used for constructing client requests that need to be executed asynchronously. Invoking a request asynchronously does the task of returning the CONTROL to the caller by returning with datatype java.util.concurrent.Future whose type is set to return the service call type. Future objects are used because they have the required methods to check whether the asynchronous calls have been completed and if yes, then retrieve the responses. They also provide the flexibility to cancel the request invocations and also check if the cancellation has been successful.

Let us understand this with the help of a random example. We know that the Future interface from the java.util.concurrent has the below functions available:

package java.util.concurrent;public interface Future<V> { // informs the executor to stop the thread execution boolean cancel(boolean mayInterruptIfRunning); // indicates whether the Future was cancelled or not boolean isCancelled(); // indicates if the executor has completed the task boolean ISDONE(); // gets the actual result from the process. // This blocks the program execution until the result is ready. V get() throws InterruptedException, ExecutionException; // also gets actual result from the process but it throws // the TimeoutException in case the result is not obtained before specified timeout V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;}

Let us consider we have this function below which is used for processing 2 Ids parallelly.

public void processIds(String userId1, String questionId){ Client client = ClientBuilder.newClient(); Future<Response> futureResponse1 = client.target("http://interviewbitserver.com/users/"+USERID).request().async().get(); Future<Order> futureResponse2 = client.target("http://interviewbitserver.com/questions/"+questionId).request().async().get(Question.class); // block the process until complete Response response1 = futureResponse1.get(); User userObject = response1.readEntity(User.class); //Do processing of userObject // Wait for 2 seconds before fetching record try { Question question = futureResponse2.get(2, TimeUnit.SECONDS); //Do Processing of question } catch (TimeoutException timeoutException ) { //handle exceptions } return;}

In the above example, we see that there are 2 separate requests getting executed parallelly. For the first future object, we AWAIT the javax.ws.rs.core.Response indefinitely using the get() method until we get the response. For the second future object, we wait for the response only for 2 seconds and if we do not get within 2 seconds, then the get() method throws TimeoutException. We can also use the isDone() method or isCancelled() method to find out whether the executors have completed or cancelled.



Discussion

No Comment Found