等待一组异步Java调用的轻量级的方式 [英] Lightweight way of waiting for a group of asynchronous Java calls

查看:92
本文介绍了等待一组异步Java调用的轻量级的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在写一些code,在一个单一的阻断方法,它调用了多个,缓慢的第三方服务是异步的。这些异步调用被包裹在code实现相同的接口方法。我们要断火异步调用和等待,直到他们都回到我们的拦截方法调用之前返回。

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.

我希望这是清楚了!

有没有实施这个合适的设计模式/库...它必须是一个相当普遍的模式。先谢谢了。

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

推荐答案

您可以使用<一个href=\"http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html\"><$c$c>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.:

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

这篇关于等待一组异步Java调用的轻量级的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆