Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel pending items from a ScheduledThreadPoolExecutor?

I have a task which requires me to schedule tasks and remove them when a certain event occurs. I'm using a ScheduledThreadPoolExecutor to schedule the tasks, that's pretty straightforward. But, I found two ways to cancel the pending items, both of them look a bit odd.

I'm curious if any of them is at production quality. If neither of them, then what do you suggest?

Here is a skeleton of what I do:

private final ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1);

public void doStuff() {
    //...
    scheduler.schedule(new Runnable() {/*...*/}, 10, TimeUnit.MILISECONDS)
}

public void actOnEvent() {
    cancelPendingItems();
    doMoreStuff();
}

public void cancelPendnigItems() {
    // TODO implement me
}

This is candidate 1:

public void cancelPendingItems() {
    scheduler.getQueue().clear();
}

This is candidate 2:

public void cancelPendingItems() {
    for (Runnable task : scheduler.getQueue()) {
        scheduler.remove(task);
    }
}

Both look like a hack to me because they depend on the ScheduledThreadPoolExecutor.queue property which isn't specified in the ScheduledExecutor interface. I'm a bit worried that I might violate an invariant of ScheduledThreadPoolExecutor and I will detect it too late.

So, are these snippets going to do what I want them to do? Are there any better/cleaner ways to do it?

like image 722
Tamas Rev Avatar asked Sep 24 '12 16:09

Tamas Rev


1 Answers

Note that ScheduledExecutorService.schedule returns a ScheduledFuture. Just store these and when your cancel method is called, use the cancel method on the stored futures to cancel their future iterations.

like image 166
Brian Avatar answered Oct 19 '22 06:10

Brian