Lightweight way of waiting for a group of asynchronous Java calls

南楼画角 提交于 2019-12-03 12:57:49

问题


We're writing some code, in a single blocking method, which calls out to multiple, slow third party services asynchronously. These async calls are wrapped in code that implement the same interface method. We wish to fire off the async calls and wait until they've all returned before returning our blocking method call.

I hope that's clear!

Is there a suitable design pattern / library for implementing this... it must be a fairly common pattern. Thanks in advance.


回答1:


You could use a CountDownLatch initialized with the number of async calls and have each async handler decrement the latch. The "outer" blocking method would simply "await" for the full countdown, e.g.:

// Untested, Java pseudocode...
public void awaitAllRemoteCalls() {
    final CountDownLatch allDoneSignal = new CountDownLatch(N);
    // For each remote N calls...
    thirdPartyAsyncCall.call(new AsyncHandler(Object remoteData) {
        // Handle the remote data...
        allDoneSignal.countDown();
    });
    allDoneSignal.await();
}



回答2:


I'm not sure how you're doing things, but I'd have whatever starts the async tasks (preferably by using an Executor) return a Future<?> for each task you start. Then you'd simply need to put all the Future<?>s in a Collection and iterate through it calling get():

List<Future<?>> futures = startAsyncTasks();
for (Future<?> future : futures) {
  future.get();
}
// all async tasks are finished

I've left out exception handling for get() here, but that's the general idea.



来源:https://stackoverflow.com/questions/4937609/lightweight-way-of-waiting-for-a-group-of-asynchronous-java-calls

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