How to make concurrent network requests using OKHTTP?
OkHttp natively supports asynchronous requests efficiently e.g. sharing the optimum number of connections.
For the second part of the question, you use a CountdownLatch or you can bridge to java Futures like the following
public class OkHttpResponseFuture implements Callback { public final CompletableFuture<Response> future = new CompletableFuture<>(); public OkHttpResponseFuture() { } @Override public void onFailure(Call call, IOException e) { future.completeExceptionally(e); } @Override public void onResponse(Call call, Response response) throws IOException { future.complete(response); }}
And call
private Future<Response> makeRequest(OkHttpClient client, Request request) { Call call = client.newCall(request); OkHttpResponseFuture result = new OkHttpResponseFuture(); call.enqueue(result); return result.future; }
At that point you can use methods like CompletableFuture.allOf
n.b. if you wrap with Futures, it can be easy to not close the Response objects when one fails.