Recently I've delved into a little bit of work using an API. The API uses the Unirest http library to simplify the work of receiving from the web. Naturally, since the data is called from the API server, I tried to be efficient by using asynchronous calls to the API. My idea is structured as follows:
- Create array of data by returning the results of futures
- Display data + additional information gathered from the data
Therefore, I need to have all the data returned before I can start the second step. My code is as follows:
Future < HttpResponse < JsonNode > > future1 = Unirest.get("https://example.com/api").asJsonAsync(new Callback < JsonNode > () {
public void failed(UnirestException e) {
System.out.println("The request has failed");
}
public void completed(HttpResponse < JsonNode > response) {
System.out.println(response.getBody().toString());
responses.put(response);
}
public void cancelled() {
System.out.println("The request has been cancelled");
}
});
Future < HttpResponse < JsonNode > > future2 = Unirest.get("https://example.com/api").asJsonAsync(new Callback < JsonNode > () {
public void failed(UnirestException e) {
System.out.println("The request has failed");
}
public void completed(HttpResponse < JsonNode > response) {
System.out.println(response.getBody().toString());
responses.put(response);
}
public void cancelled() {
System.out.println("The request has been cancelled");
}
});
doStuff(responses);
How would I make it so doStuff is called only after both of the futures are finished?
There are a few options. The code you have now calls
doStuff
from the same thread where you make your requests. If you want to block until both requests have completed you could use a CountDownLatch. Something like:If you don't want to block that thread until both calls are complete, you could have each of your anonymous inner Callback classes increment an AtomicInteger. When the count is 2 you'd call
doStuff
. Something like: