等待一组异步 Java 调用的轻量级方法

发布于 2024-10-16 11:46:13 字数 166 浏览 2 评论 0原文

我们正在单个阻塞方法中编写一些代码,该方法异步调用多个缓慢的第三方服务。这些异步调用包装在实现相同接口方法的代码中。我们希望触发异步调用并等待它们全部返回,然后再返回阻塞方法调用。

我希望这是清楚的!

是否有合适的设计模式/库来实现这个......它必须是一个相当常见的模式。提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

別甾虛僞 2024-10-23 11:46:13

您可以使用 CountDownLatch 使用异步调用的数量进行初始化,并让每个异步处理程序递减锁存器。 “外部”阻塞方法将简单地“等待”完整倒计时,例如:

// 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();
}

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();
}
忆梦 2024-10-23 11:46:13

我不确定你是如何做事的,但我会让启动异步任务的任何东西(最好通过使用 Executor)返回 Future对于您开始的每项任务。然后,您只需将所有 Future 放入 Collection 中,并调用 get() 对其进行迭代:

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

I这里省略了 get() 的异常处理,但这就是总体思路。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文