These days I am doing a bit of Java programming. One of the new Features that I learned recently is Future.
A Future is a representation of the result of an asynchronous computation. A Future has methods to check if the computation has completed and retrieve the result of the task. You can also cancel a computation if you choose to, unless the computation has already completed.
A couple of notable methods in Future
- isDone() returns a boolean representing if the task is done. This method is used for polling to check if the task is done.
- Get() returns the final result of the Future,it is a blocking method which waits until the computation is done. This method take a timeout argument in milliseconds. Which specifies the maximum amount of time we wait for the computation to complete. If the task is not done in the specified time, a timeout exception will be thrown.
- Cancel() will abort the computation.
Let’s see the context in which we can see the usage of
Futures.Think of a hypothetical scenario in which we have to fire a http
request asynchronously and do some random task while waiting for the response
to come.
 The steps involved
look like the following     
- Fire http request and get the Future representing the outcome(i.e no waiting for the request to finish).
- Do some random task
- Check if the response is ready. Here we use the get() method to block and retrieve the response.
To demonstrate this with a code I will use an
AsyncHttpClient from NING. This
Client allows us to send out http requests and receive the response
asynchronously. 
 If you are using
maven for your dependency management you can add NING to your project by adding
this dependency.
<groupId>com.ning</groupId>
<artifactId>async-http-client</artifactId>
<version>1.8.11</version>
</dependency>
Then your code will look like the following code snipnet
. I am using the RequestBuilder utility from the same  library that allow me set
the url, headers and other properties corresponding to http request.
RequestBuilder requestBuilder = new
com.ning.http.client.RequestBuilder();
requestBuilder.setUrl("http://www.example.com");
AsyncHttpClient client = new AsyncHttpClient();
Future response = asyncHttpClient.executeRequest(requestBuilder.build());
//do some task here while waiting for the response
//check if the task is done.If not done , do some other task
If(!response.isDone()) {
// Do some other task 
}
//at this point , block and wait for the response
try {
NettyResponse  value =(NettyResponse) response.get();
}
Catch(TimeoutException ex) {
//Log the exception or bubble it
}
Catch (ExecutionException ex) {
//Log the exception 
}
Catch (Exception ex) {
//Log the exception 
}
 
No comments:
Post a Comment