An easy way to wait for a group of Java asynchronous calls

We write some code in one locking method, which asynchronously calls several slow third-party services. These asynchronous calls are wrapped in code that implements the same interface method. We want to disable asynchronous calls and wait until they return before returning our call to the lock method.

I hope this is clear!

Is there a suitable design template / library to implement this ... it should be fairly common. Thanks in advance.

+8
java asynchronous synchronous
source share
2 answers

You can use a CountDownLatch initialized by the number of asynchronous calls, and each async handler will reduce the commit. The โ€œexternalโ€ blocking method simply โ€œcame to lifeโ€ for a complete countdown, for example:

 // 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(); } 
+9
source share

I'm not sure how you do this, but I would have everything that ran the async tasks (preferably using Executor ) to return Future<?> For every task that you run. Then you just need to put all the Future<?> In the Collection and loop through the get() call:

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

I left the exception handling for get() here, but thats the general idea.

+2
source share

All Articles