1

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;
}
Gwenc37
  • 2,064
  • 7
  • 18
  • 22
AKIWEB
  • 19,008
  • 67
  • 180
  • 294

2 Answers2

1

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.

Prateek
  • 523
  • 2
  • 13
1

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks Stephen for the suggestion. So that means I won't be needing while loop right? And I can measure the time elapsed in the finally block then? – AKIWEB Feb 12 '13 at 03:33
  • 1
    You don't really need a finally either. You are only going to get an `InterruptedException` if some other thread interrupts the current one. In that case, I hardly think you care what the timing was ... 'cos it won't be a meaningful measure of anything. – Stephen C Feb 12 '13 at 09:51