简体   繁体   English

在Java中等待异步http请求

[英]waiting on asynchronous http requests in java

I'm using Jetty HTTP Client to make about 50 HTTP calls asynchronously. 我正在使用Jetty HTTP Client异步进行约50个HTTP调用。 The code looks something like this: 代码看起来像这样:

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");

It's calling a rest service that returns back some data about the address. 它正在调用Rest服务,该服务返回有关该地址的一些数据。 What I expect it to do is this: 我期望它是这样的:

  1. Make 50 asynchronous (non-blocking) http calls. 进行50次异步(非阻塞)http调用。
  2. The thread will wait until all 50 are finished. 线程将等待,直到全部50个线程完成。

However, it's not working. 但是,它不起作用。 It works fine if I don't have the while loop, but I need to wait until all 50 are done. 如果没有while循环,它会很好地工作,但是我需要等到所有50个都完成之后。 Is there some way to wait until all 50 are done? 有没有办法等到全部50个完成?

Also I know about ExecutorService and multiple thread solution, but I need a single thread solution with non-blocking IO. 我也了解ExecutorService和多线程解决方案,但是我需要具有无阻塞IO的单线程解决方案。

Use the java.util.concurrent.CountDownLatch to manage this. 使用java.util.concurrent.CountDownLatch进行管理。

Example from Eclipse Jetty 8.1.10.v20130312's Siege.java test class: 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)

Note: ConcurrentExchange is a private class within Siege.java. 注意: ConcurrentExchange是Siege.java中的私有类。

Then in your HttpExchange object, use the CountDownLatch.countDown() call in the following methods 然后在您的HttpExchange对象中,在以下方法中使用CountDownLatch.countDown()调用

Note that all of the examples use a AtomicBoolean counted to make sure that they are only counted once. 请注意,所有示例都使用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