We help IT Professionals succeed at work.
Get Started

Refactoring a java code and correct use of Futures

Rohit Bajaj
Rohit Bajaj asked
Last Modified: 2016-04-26
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 = unirest.post(webhookEndpoint).header("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
This problem has been solved!
Unlock 1 Answer and 1 Comment.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE