Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setRemoveOnCancelPolicy for Executors.newScheduledThreadPool(5)

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?

like image 463
Kaloyan Roussev Avatar asked Apr 20 '16 15:04

Kaloyan Roussev


People also ask

How do I cancel a scheduled executor?

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.

How do I stop a scheduler in Java?

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.


1 Answers

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);
like image 181
AdamSkywalker Avatar answered Oct 13 '22 21:10

AdamSkywalker