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.
Advertisement
Answer
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);