Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lightweight way of waiting for a group of asynchronous Java calls

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.

like image 809
rich Avatar asked Feb 08 '11 19:02

rich


1 Answers

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();
}
like image 119
maerics Avatar answered Oct 24 '22 12:10

maerics