How to stop the execution of Executor ThreadPool in java?

I am working on the Executors in java to concurrently run more threads at a time. I have a set of Runnable Objects and i assign it to the Exceutors.The Executor is working fine and every thing is fine.But after all the tasks are executed in the pool ,the java program is not terminated,i think the Executor takes some time to kill the threads.please anyone help me to reduce the time taken by the executor after executing all tasks.

13.10.2009 18:27:12
2 ОТВЕТА
РЕШЕНИЕ

The ExecutorService class has 2 methods just for this: shutdown() and shutdownNow().

After using the shutdown() method, you can call awaitTermination() to block until all of the started tasks have completed. You can even provide a timeout to prevent waiting forever.

You might want to click on some of these links that I'm providing. They go straight to the docs where you can readup on this stuff yourself.

27
13.10.2009 18:38:24
How i can ensure that all the tasks are committed,i need all the tasks should commit its execution
Rajapandian 13.10.2009 18:33:40
@Rajapandian The definition of shutdown is that it waits for all tasks to complete, but does not allow new ones to start. How does that not do what you want?
Kathy Van Stone 13.10.2009 18:44:47
please any one tell me why my java program takes time to stop execution even after the Executor finish all its task.
Rajapandian 13.10.2009 20:04:28
That seems to be a separate question. You can use something like 'jstack' or 'jconsole' to see which threads are running and what they're waiting for.
Outlaw Programmer 13.10.2009 20:27:42

executor.shutdown() with awaitTermination(timeout) does not kill threads. (ie), if your runnable task is inside a polling loop, it does not kill the task. All it does is to interrupt its runnable tasks when the timeout is reached. So, in the code for your runnable class, if you wait on some condition, you may want to change the condition as,

while (flagcondition && !Thread.currentThread().isInterrupted()) {}

This ensures that the task stops when the thread is interrupted as the while loop terminates. Alternately, you might want to catch the interrupted exception and set flag=false in the catch block to terminate the thread.

try {
    // do some stuff and perform a wait that might throw an InterruptedException
} catch (InterruptedException e) {
    flagcondition = false;
}

You might also want to use a profiler to examine why some threads have not proceeded to completion.

12
3.06.2012 19:20:41