I have a class as below :
public class GrpcApiRunnable implements Runnable{
private final int noOfThreads;
private final long duration;
private final CountDownLatch countDownLatch;
@Override
public void run() {
ExecutorService executorService = Executors.newFixedThreadPool(noOfThreads);
long serviceStartTime = System.currentTimeMillis();
long serviceEndTime = serviceStartTime + duration;
while(System.currentTimeMillis()<serviceEndTime) {
executorService.submit(() -> {
//do something
});
}
//Wait for all the threads to complete till the specified duration
awaitTerminationAfterShutdown(executorService,duration);
countDownLatch.countDown();
}
}
I want to call the runnable as below:
public JsonObject performanceTestV21(long duration, int noOfThreads) throws InterruptedException {
ExecutorService outerExecutorService = Executors.newFixedThreadPool(getGrpcTestInfos().size());
CountDownLatch countDownLatch = new CountDownLatch(getGrpcTestInfos().size());
for (GrpcTestInfo grpcTestInfo : getGrpcTestInfos()) {
outerExecutorService.submit(new GrpcApiRunnable(noOfThreads,duration,countDownLatch));
}
countDownLatch.await();
return new JsonObject(performanceMatrix);
}
Looks like the countDownLatch count is not getting decremented. The outerExecutorService will create a threadpool of size 23 in my case and I want to wait until all the threads inside the runnable is complete. Where is the mistake?
Moved the countDown() to finally block. The //do something
block was throwing exception and hence countdown was never getting decremented.