22

I made a fixed size thread pool with Executors.newFixedThreadPool(2), and I executed 10 Runnable objects. I set breakpoints and traced through the execution. However, fixedSizeThreadPool.awaitTermination() does not allow me to continue even though all the tasks are done.

Basically:

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; ++i) {
    fixedSizeThreadPool.execute(myRunables[i]);
}
try {
    fixedSizeThreadPool.awaitTermination(timeout, timeoutUnits);
} catch (Exception e) { }
System.out.println("done!");

But this always gets stuck on awaitTermination. What's wrong?

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Kevin
  • 1,080
  • 3
  • 15
  • 41

2 Answers2

34

As Peter pointed out, shutdown() must be called first.

source: javadoc

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
  • So if I want to keep reusing the threadpool, I should use invokeAll, and keep checking the list of Futures until they're all completed? – Kevin Aug 14 '11 at 19:31
  • that's correct - `awaitTermination` is only used in the context of shutting it down – Paul Bellora Aug 14 '11 at 19:33
  • 1
    @kevin: invokeall returns only after ALL tasks have completed, either normally or with exception. You check Futures to get results in this case, not to see if they have completed (they have). – Peter Štibraný Aug 14 '11 at 19:34
  • @Peter you're absolutely right. I mistakenly thought that invokeAll was not blocking. – Kevin Aug 14 '11 at 19:37
  • @Peter - nice catch. I assume this is what he wants to achieve though based on his code. – Paul Bellora Aug 14 '11 at 19:37
2

You could also use ExecutorService#invokeAll. It blocks until all tasks are done or the timeout is reached. It's a little cleaner than using shutdown, if your ExecutorService contains other tasks as well especially scheduled tasks. These would also be affected by a call to shutdown.

emboss
  • 38,880
  • 7
  • 101
  • 108