How to setRemoveOnCancelPolicy for Executors.newScheduledThreadPool (5)

I have it:

ScheduledExecutorService scheduledThreadPool = Executors .newScheduledThreadPool(5); 

Then I run the task as follows:

 scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS); 

I keep a reference to the future as follows:

 ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS); 

I want to be able to undo and delete the future

 scheduledFuture.cancel(true); 

However, this SO answer notes that canceling does not delete it, and adding new tasks will end with many tasks that cannot be GCed.

stack overflow

They mention something about setRemoveOnCancelPolicy , however this scheduledThreadPool does not have such a method. What should I do?

+6
java multithreading concurrency
Apr 20 '16 at 15:08
source share
1 answer

This method is 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 the newScheduledThreadPool executor class and similar methods.

 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } 

In short, you can use the executor service link to call the method

 ScheduledThreadPoolExecutor ex = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5); ex.setRemoveOnCancelPolicy(true); 

or create new ScheduledThreadPoolExecutor yourself.

 ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(5); ex.setRemoveOnCancelPolicy(true); 
+8
Apr 20 '16 at 15:15
source share



All Articles