rranke
rranke

Reputation: 33

How to measure the elapsed time of ASYNC sent HTTPRequest with Java 11 standard HTTPClient?

In one method, I create and send some HTTPRequests async, and add the CF to a list:

// HTTPClient is Java11 standard, package java.net.http;
CompletableFuture<HttpResponse<String>> httpResponseCF = this.httpClient.sendAsync(httpRequest, BodyHandlers.ofString());
list.add(httpResponseCF);

Later, in another method, I periodically check every 1second if some of my async sent HTTPRequests have already received:

for(CompletableFuture<HttpResponse<String>> httpResponseCF : list){
  if (httpResponseCF.isDone()) {
    //print out: The time between sending HTTPRequest and receiving HTTPResponse is 25ms
  }
}

The question is, how to measure the exact elapsed request-time?

Upvotes: 1

Views: 1535

Answers (1)

daniel
daniel

Reputation: 3268

Something like the following should do the trick:

long start = System.nanoTime();
CompletableFuture<HttpResponse<String>> httpResponseCF = 
    this.httpClient.sendAsync(httpRequest, BodyHandlers.ofString()).
    whenComplete((r,t) -> System.out.println("elapsed ns: "
                           + (System.nanoTime() - start)));

Disclaimer: I haven't actually compiled the above... It's also not the exact time but the best approximation you can get. As with everything, the exact time is impossible to measure.

Upvotes: 1

Related Questions