Here is my code snippet.
ExecutorService executor = Executors.newFixedThreadPool(ThreadPoolSize);
while(conditionTrue)
{
ClassImplementingRunnable c = new Cl
You generally use the following idiom:
executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
What i want to achieve here is that i want to wait for all the threads in the threadpool to have finished the execution and then i want to shutdown the executor.
That is what executor.shutdown();
does. If you want to shutdown immediately you need to use shutdownNow()
shutdown
is a "soft" order and won't abruptly shut down the executor. It will do just what you want: refuse any new tasks, wait for all submitted tasks to complete, and then shut down.
Add awaitTermination
to your code in order to block until the executor service is shut down.
In the documentation there's also this code that covers all the angles:
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}