Jetty HTTP クライアントを使用して、非同期で約 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");
アドレスに関するデータを返す残りのサービスを呼び出しています。私が期待しているのはこれです:
- 50 回の非同期 (ノンブロッキング) http 呼び出しを行います。
- スレッドは、50 個すべてが終了するまで待機します。
しかし、それは機能していません。while ループがなくても問題なく動作しますが、50 個すべてが完了するまで待つ必要があります。50個すべてが完了するまで待つ方法はありますか?
ExecutorService とマルチスレッド ソリューションについても知っていますが、ノンブロッキング IO を備えたシングル スレッド ソリューションが必要です。