How to remove a task from ScheduledExecutorService?

I have a ScheduledExecutorService service that periodically performs several different tasks using .scheduleAtFixedRate(Runnable, INIT_DELAY, ACTION_DELAY, TimeUnit.SECONDS);

I also have another Runnable that I use with this scheduler. The problem starts when I want to remove one of the tasks from the scheduler.

is there any way to do this?

Am I doing it right using the same scheduler for different tasks? What is the best way to implement this?

+42
java android scheduledexecutorservice
Jan 20 '13 at 10:07
source share
2 answers

Just undo the future returned by scheduledAtFixedRate() :

 public static void main(String[] args) throws InterruptedException { ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); Runnable r = new Runnable() { @Override public void run() { System.out.println("Hello"); } }; ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(r, 1L, 1L, TimeUnit.SECONDS); Thread.sleep(5000L); scheduledFuture.cancel(false); } 

Another thing to note is that undoing does not remove the task from the scheduler. All this ensures that the isDone method always returns true. This can lead to a memory leak if you continue to add such tasks. For example, if you start a task based on some client activity or a user interface button, repeat it n times and exit. If this button is pressed too many times, you can get a large pool of threads that cannot be garbage collected because the scheduler still has a link.

You can use setRemoveOnCancelPolicy (true) in the ScheduledThreadPoolExecutor class, available in Java 7 onwards. For backward compatibility, the default value is false.

+61
Jan 20 '13 at 10:26
source share

If your instance of ScheduledExecutorService extends ThreadPoolExecutor (for example, ScheduledThreadPoolExecutor ), you can use remove(Runnable) (but see the note in its javadoc: β€œIt may not delete tasks that have been converted to other forms before being placed in the internal queue.”) Or purge() .

0
Dec 20 '17 at 22:20
source share



All Articles