等待一组异步 Java 调用的轻量级方法
我们正在单个阻塞方法中编写一些代码,该方法异步调用多个缓慢的第三方服务。这些异步调用包装在实现相同接口方法的代码中。我们希望触发异步调用并等待它们全部返回,然后再返回阻塞方法调用。
我希望这是清楚的!
是否有合适的设计模式/库来实现这个......它必须是一个相当常见的模式。提前致谢。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
CountDownLatch
使用异步调用的数量进行初始化,并让每个异步处理程序递减锁存器。 “外部”阻塞方法将简单地“等待”完整倒计时,例如: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.:我不确定你是如何做事的,但我会让启动异步任务的任何东西(最好通过使用
Executor
)返回Future
对于您开始的每项任务。然后,您只需将所有Future
放入Collection
中,并调用get()
对其进行迭代: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 aFuture<?>
for each task you start. Then you'd simply need to put all theFuture<?>
s in aCollection
and iterate through it callingget()
:I've left out exception handling for
get()
here, but that's the general idea.