I have this:
ScheduledExecutorService scheduledThreadPool = Executors
.newScheduledThreadPool(5);
Then I start a task like so:
scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
I preserve the reference to the Future this way:
ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
I want to be able to cancel and remove the future
scheduledFuture.cancel(true);
However this SO answer notes that canceling doesn't remove it and adding new tasks will end in many tasks that can't be GCed.
https://stackoverflow.com/a/14423578/2576903
They mention something about setRemoveOnCancelPolicy
, however this scheduledThreadPool
doesn't have such method. What do I do?
Learn to cancel a task submitted to an executor service if the task still has to be executed and/or has not been completed yet. We can use the cancel() method of Future object that allows making the cancellation requests.
The cancel() method is used to cancel the timer task. The cancel() methods returns true when the task is scheduled for one-time execution and has not executed until now and returns false when the task was scheduled for one-time execution and has been executed already.
This method is declared in ScheduledThreadPoolExecutor.
/**
* Sets the policy on whether cancelled tasks should be immediately
* removed from the work queue at time of cancellation. This value is
* by default {@code false}.
*
* @param value if {@code true}, remove on cancellation, else don't
* @see #getRemoveOnCancelPolicy
* @since 1.7
*/
public void setRemoveOnCancelPolicy(boolean value) {
removeOnCancel = value;
}
This executor is returned by Executors class by newScheduledThreadPool and similar methods.
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
So in short, you can cast the executor service reference to call the method
ScheduledThreadPoolExecutor ex = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
ex.setRemoveOnCancelPolicy(true);
or create new ScheduledThreadPoolExecutor
by yourself.
ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(5);
ex.setRemoveOnCancelPolicy(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With