Reputation: 19612
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;
}
Upvotes: 1
Views: 269
Reputation: 718788
Q: Do you need the while
? A: No.
The previous awaitTermination
call won't return until either the service has terminated, or (2^63 - 1)
seconds have elapsed. (That is a very long time.)
UPDATE - The updated version looks OK to me.
Upvotes: 1
Reputation: 551
You are not required to re-invent the wheel. You can use http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CompletionService.html
This works pretty fine. This should solve your problem statement too.
Upvotes: 1