Blue Label
Blue Label

Reputation: 437

shutdown all the task in ThreadPool java 5

I am using thread executor of Java 5 , and running several tasks which implements the interface callable.

The issue that my task running in loop and once I want to exit from my application I am calling the shutdownNow() method ,which is not good because it stop all task that finished work

And I have 2 task which is not finished so 2 thread still running even after I close my application.

Is there an API that can insure that all my threads stopped immediately or I should implements some interface or add stop method to my each thread.

Because the interface Callable has just one method call. And there is not stop method.

Upvotes: 0

Views: 236

Answers (2)

Tudor
Tudor

Reputation: 62439

If you need to order all thread to stop then you should add a flag test inside the thread code:

while(!stop) {
    // do work
}

And set the flag to true when you want to exit the program. Don't forget to make it volatile.

If you only want to wait for all of them to finish before exiting the program, use:

executor.awaitTermination(60, TimeUnit.SECONDS));

Upvotes: 0

BalusC
BalusC

Reputation: 1108557

Read the ExecutorService#shutdownNow() javadoc:

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

So, you need to regularly check Thread#isInterrupted() inside the call() yourself. You can do that in for example some while loop.

Upvotes: 1

Related Questions