簡體   English   中英

在Java中等待異步http請求

[英]waiting on asynchronous http requests in java

我正在使用Jetty HTTP Client異步進行約50個HTTP調用。 代碼看起來像這樣:

List<Address> addresses = getAddresses();
final List<String> done = Collections.synchronizedList(new LinkedList<String>());
List<ContentExchange> requests;
for (Address address : addresses) {
    ContentExchange ce = new ContentExchange() {
        @Override
        protected void onResponseComplete() throws IOException {
            //handle response
            done.add("done");
        }
    }
    ce.setURL(createURL(address));
    requests.add(ce);
}
for (ContentExchange ce : requests) {
    httpClient.send(ce);
}

while (done.size() != addresses.size()) {
    Thread.yield();
}

System.out.println("All addresses processed");

它正在調用Rest服務,該服務返回有關該地址的一些數據。 我期望它是這樣的:

  1. 進行50次異步(非阻塞)http調用。
  2. 線程將等待,直到全部50個線程完成。

但是,它不起作用。 如果沒有while循環,它會很好地工作,但是我需要等到所有50個都完成之后。 有沒有辦法等到全部50個完成?

我也了解ExecutorService和多線程解決方案,但是我需要具有無阻塞IO的單線程解決方案。

使用java.util.concurrent.CountDownLatch進行管理。

Eclipse Jetty 8.1.10.v20130312的Siege.java測試類的示例

final CountDownLatch latch = new CountDownLatch(concurrent);   

for (int i=0;i<concurrent;i++)
{
    ConcurrentExchange ex = new ConcurrentExchange(client,latch,uris,repeats);
    if (!ex.next()) // this executes the client.send()
    {
        latch.countDown(); // count down if client.send() was in error
    }
}

latch.await(); // wait for all ConcurrentExchange's to complete (or error out)

注意: ConcurrentExchange是Siege.java中的私有類。

然后在您的HttpExchange對象中,在以下方法中使用CountDownLatch.countDown()調用

請注意,所有示例都使用AtomicBoolean counted ,以確保僅計數一次。

if (!counted.getAndSet(true)) // get the value, then set it to true
{
    // only get here if counted returned false. (and that will only happen once)
    latch.countDown(); // count down this exchange as being done.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM