iddqd
iddqd

Reputation: 1305

Best way to stop a ScheduledThreadPoolExecutor

I am using a single ScheduledThreadPoolExecutor to manage multiple tasks and would like to add the option to stop them.
I understand the difference between shutdown and shutdownNow on a regular executor service, and am interested in understanding how it will affect tasks in a ScheduledThreadPoolExecutor - where tasks are also scheduled to be run on a regular interval.
Given a running ScheduledThreadPoolExecutor that has both running tasks, one time tasks schedled to be run in the future, and tasks that are scheduled to be run in a constant interval (once every X minutes). What will be the best way to implement the following "commands" :

  1. Stop everything now. Stop all running tasks immediately, Do not run any tasks that were already scheduled but did not yet start.
  2. Currently running threads can be completed if required. Do not run any tasks that were already scheduled but did not yet start.

Upvotes: 2

Views: 1357

Answers (2)

A_C
A_C

Reputation: 925

  1. Stop everything now. Stop all running tasks immediately, Do not run any tasks that were already scheduled but did not yet start.

You can use the method : public List<Runnable> shutdownNow() , but please note that the currently executing threads may not immediately terminate. If you want to do that, then you have to find a way to signal a killing of the process via a separate thread or something.

From the Javadocs: There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. This implementation cancels tasks via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

  1. Currently running threads can be completed if required. Do not run any tasks that were already scheduled but did not yet start.

This can be achieved by using the method: public void shutdown()

From the Javadocs: If the ExecuteExistingDelayedTasksAfterShutdownPolicy has been set false, existing delayed tasks whose delays have not yet elapsed are cancelled. And unless the ContinueExistingPeriodicTasksAfterShutdownPolicy has been set true, future executions of existing periodic tasks will be cancelled.

Upvotes: 4

Thilo
Thilo

Reputation: 262494

You can configure this using

So your two cases are

  1. call shutdownNow
  2. set continue policy to false, then call shutdown

Upvotes: 1

Related Questions