How to cancel pending items from a ScheduledThreadPoolExecutor? How to cancel pending items from a ScheduledThreadPoolExecutor? multithreading multithreading

How to cancel pending items from a ScheduledThreadPoolExecutor?


Note that ScheduledExecutorService.schedule returns a ScheduledFuture. Just store these and when your cancel method is called, use the cancel method on the stored futures to cancel their future iterations.


I would use a List<Future>:

private final List<Future> futures = ...public void doStuff() {    futures.add(scheduler.schedule(new Runnable() {/*...*/}, 10,        TimeUnit.MILISECONDS));}public void cancelPendingItems() {    for(Future future: futures)        future.cancel(true);    futures.clear();}


Future.cancel(boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

Or you can also use ScheduledThreadPoolExecutor#shutdownNow

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. This implementation cancels tasks via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

So you need to handle InterruptedException to allow safe exit of threads which are being canceled.