2

Before I jump into the specifics of the question, I want to give the context of the problem. Basically, my code looks like

for(int i = 0; i < n; i++){
    startTime = System.currentTimeMillis();
    result = doSomething();
    endTime = System.currentTimeMillis();
    responseTime.add(endTime - startTime);
    results.add(result);
} 
print(results and responseTime);

Now what i want to do is run doSomething() as a completableFuture and get the responseTime as mentioned above. But since doing something like this would be totally incorrect --

for(int i = 0; i < n; i++){
    startTime = System.currentTimeMillis();
    resultCF = CompletableFuture.supplyasync(() -> doSomething());
    endTime = System.currentTimeMillis();
    responseTime.add(endTime - startTime);
    results.add(resultCF); //result is to store the completableFutures
}
CompletableFuture.allOf(results.toArray(new CompletableFuture[results.size()])).join();
print(i.get() for i in results and responseTimes);

since it would defeat the purpose of getting the execution time of each doSomething(). So, is there any way I can get the response time of each completableFuture? Also, i would need the results arraylist containing the completableFutures(resultCF) at the end of the loop.

T.P.
  • 83
  • 3
  • 12

1 Answers1

5

The easiest may be to just add a stage to resultCF, which itself adds the response time to the list. resultCF will be completed after this part is done:

resultCF = CompletableFuture.supplyasync(() -> doSomething())
              .thenApply(s -> {
                  responseTime.add(System.currentTimeMillis() - startTime);
                  return s;
               });
results.add(resultCF);
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • 2
    `System::currentTimeMillis` is not a monotonic clock, meaning it is subject to arbitrary jumps when the system synchronizes its time. Therefore, it's not reliable for time deltas; for that, you can use `System::nanoTime`. See https://stackoverflow.com/a/18994289/7096763 – MikaelF Jun 15 '22 at 01:21