Java 11 HttpClient Setting Maximum number of connections

Viewed 400

I am trying to set maximum open httpconnection at particular time to 10. If a 11th request comes, it should wait for one of the httpconnection to be free. My code is given below. I am not sure how to test if it works as expected. Could some one verify this?

private final ExecutorService executorService = Executors.newFixedThreadPool(10);

  private final HttpClient httpClient = HttpClient.newBuilder()
          .executor(executorService)
          .build();

//BElow code is inside my method

List<CompletableFuture<String>> result = targets.stream()
                        .map("myjson"-> httpClient.sendAsync(
                                HttpRequest.newBuilder()
                                        .POST(HttpRequest.BodyPublishers.ofString("myjson"))
                                        .uri(URI.create("myURl"))
                                        .setHeader("Authorization", "Basic =")
                                        .build(),
                                HttpResponse.BodyHandlers.ofString())
                                .thenApply(response -> response.body()))
                        .collect(Collectors.toList());
                


                for (CompletableFuture<String> future : result) {
                    System.out.println(future.get());
                   
                }
0 Answers
Related