16

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?

Community
  • 1
  • 1
Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180

1 Answers1

17

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);
AdamSkywalker
  • 11,408
  • 3
  • 38
  • 76
  • What do you mean cast the executor service reference? Also how do I create a ScheduledThreadPoolExecutor by myself, what do you mean by that? – Kaloyan Roussev Apr 20 '16 at 15:51
  • 2
    Damn. I am developing an Android Application and this call `setRemoveOnCancelPolicy` requires API level 21 and my project supports API way back to 14. Is there another way to remove tasks? – Kaloyan Roussev Apr 20 '16 at 21:17
  • Is there any chance that cancel(false) will raise execipion? The java doc does not declare any exceptions. – JaskeyLam Jul 15 '16 at 05:28
  • @Jaskey canceling future should raise CancellationException on a caller thread that executes #get method, it should not throw exception in invoker thread – AdamSkywalker Jul 15 '16 at 09:00