Refactoring a java code and correct use of Futures

Rohit Bajaj
Rohit Bajaj used Ask the Experts™
Currently in my java code i am having the following class :
This is just an asynchronous way to make  HTTP post request with a json string.
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.async.Callback;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.util.concurrent.Future;

public class WebHookAdapter {
    private static Unirest unirest = new Unirest();
    static String webhookEndpoint;

    public static void main(String[] args) {
        Future<HttpResponse<JsonNode>> future = send("ldjflksdfj");


    public static Future send(String text) {
        String json = "{\"text\" : \"" + text + "\"}";
        Future<HttpResponse<JsonNode>> future;

        future ="Content-Type", "application/json").body(json).asJsonAsync(new Callback<JsonNode>() {
            public void completed(HttpResponse<JsonNode> httpResponse) {


            public void failed(UnirestException e) {


            public void cancelled() {

        return future;

Open in new window

Here i am using unirest for java to just make an http post call.

To make the http calls non blocking i used the Future version.
Now in the main method i am using :        Future<HttpResponse<JsonNode>> future = send("ldjflksdfj");

what do i do with this future.
If i use future.get()... i read it blocks...
In the case where i will be doing multiple http post request asynchoronously.
Is this a correct approach ??

Also the new CallBack<...code can i move it out of the method. Whats the general practice.
Is this the way to use it. Can you suggest a better approach to this problem (Making multiple asycn http post request)

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
If you want to do multiple http requests, you send off the requests and collect up the Futures you get back and put them on a list.

Then you can walk that list checking for "isDone" on each of the futures - that won't block - and when they are done get the results and process them.

Or if you are sending off a set of requests as a group - take a look at invokeAll() on the executor:

It basically does all of this for you in one step.  That's assuming you have access to the executor that is running the tasks.


Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial