How to wait for all requests to finish

陌路散爱 提交于 2019-12-12 14:30:41

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/28548375/how-to-wait-for-all-requests-to-finish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!