Waiting all threads in a fixed thread pool

Hello, may I know how can I wait for all the threads in a fixed thread pool to be completed, without calling shutdownNow?

Executor pool = Executors.newFixedThreadPool(nThreads);

for(int i = 0; i < 10000; i++)

pool.execute(new StockHistoryRunnable(code));

// blah blah blah

//

// I would like to wait for all the 10000 task to be completed. There is a method named

// awaitTermination. However, in order to use the method, I have to first call shutdownNow.

// I do not want to do so, because I need to re-use the pool later.

//

[875 byte] By [KwangHooia] at [2007-11-27 7:04:18]
# 1

Hi

The thread pools are basically used for running asynchronously.So that is why there will not be any direct way to wait till all threads are completed.

One way i can think is to have a static variable set to nThreads . decrement the variable when each threads job is finished . Wait for the count to become 0 in main thread

Vijay

bhvijaya at 2007-7-12 18:55:34 > top of Java-index,Core,Core APIs...
# 2
Do you means using CountDownLatch?Thank you.
KwangHooia at 2007-7-12 18:55:34 > top of Java-index,Core,Core APIs...
# 3
yes
bhvijaya at 2007-7-12 18:55:34 > top of Java-index,Core,Core APIs...
# 4

You could retrieve all the "Future" instances returned by calling "submit" on your Executor and then have a Thread sequentially wait for the completion of all these individual tasks by using "get". Of course, this will require some synchronization if it is possible that new tasks get queued while you are already waiting for the original ones to be completed. But this way you can easily find out when all tasks have completed.

Dalzhima at 2007-7-12 18:55:34 > top of Java-index,Core,Core APIs...