RajV
RajV

Reputation: 7200

How to wait for all requests to finish

I am using ning AsyncHttpClient from a command line program. I need to wait for all requests to end so I can safely call close() on the client. The challenge is that I make many requests from many different parts of the program. Stripped own code below that shows one scenario where I do a nested HTTP request from the onCompleted of another request:

final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

Future<Response> f1 = asyncHttpClient.prepareGet(url).execute(
    new AsyncCompletionHandler<Response>() {

        public Response onCompleted(Response response)
            throws Exception {

            //Make more HTTP calls
            Future f2 = asyncHttpClient.prepareGet(url).execute(...);

            return response;
        }
    });

This is an example code only. Real code is more complex and has many more HTTP calls. What will be the best way to make sure all calls are finished before I call close() for the client?

Upvotes: 5

Views: 1505

Answers (1)

Tim Van Laer
Tim Van Laer

Reputation: 2534

For smaller number of requests, collecting all Futures and then use CompletableFuture.allOf(futureCollection).get() might work.

According to the docs, this could work as well (not tested yet)

((DefaultAsyncHttpClient)asyncHttpClient)
  .getEventLoopGroup()
  .awaitTermination(1, TimeUnit.MINUTES);

Upvotes: 1

Related Questions