I am using Executor service
in one of my Multithreaded code
. I am trying to see whether all of my threads are finished doing their job then afterwards I need to do certain task.
Currently I need to measure the time elapsed, so I can only measure the time elapsed only after all the threads has finished executing there job. So I have this code currently? And I am measuring time elapsed
in the finally block
.
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
long startTime = System.nanoTime();
try {
for (int i = 0; i<noOfThreads; i++) {
service.submit(new Task());
}
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
//Do I need this while block here?
while (!service.isTerminated()) {
}
} catch (InterruptedException e) {
//Log exception here
} finally {
long estimatedTime = System.nanoTime() - startTime;
logTimingInfo(estimatedTime, noOfTasks, noOfThreads);
}
I am not sure whether I need while loop
here or not? Is the way I am currently doing it right or not?
Updated Code:-
So below code should work fine. Right?
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
long startTime = System.nanoTime();
try {
for (int i = 0; i<noOfThreads; i++) {
service.submit(new Task());
}
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
//Log exception here
} finally {
long estimatedTime = System.nanoTime() - startTime;
}