Description
Affects: 5.3.17
Hello everyone,
I am working on a scheduling solution and I want to cancel a scheduled task on demand. I am using ScheduledTask
which has a cancel()
method:
If I call it, it cancels the task, and it never executes it again unless I resume the task, so, everything is good as expected. But there is a use case which is a problem for me.
I see that the call future.cancel(true);
means that if the task is currently running it interrupts it immediately, without letting it finish, which could cause issues depending on the task performed. This is because the call is obligatory done with the boolean true, without any other option.
Wouldn't it be more flexible to allow cancel()
to take this into consideration? It could be enough to create another method cancel(boolean mayInterruptIfRunning);
.
or even removing the final
accessor from this class:
public final class ScheduledTask {....}
since because of this I can't extend from it and overwrite the method mentioned. I think would be useful to have the chance to make more flexible this behavior.
Of course, please tell me if I am missing some considerations about why this class has to be final
and this future.cancel();
method is called always mandatory with true
.
If in the end you consider any of the changes I proposed, I would be happy to contribute.
My proposed solution:
public final class ScheduledTask {
// . . .
/**
* Trigger cancellation of this scheduled task with optional interruption if running.
*
* @param mayInterruptIfRunning if true, it will force interruption the task if running. If false, it will let it finish before cancelling.
*/
public void cancel(final boolean mayInterruptIfRunning) {
ScheduledFuture<?> future = this.future;
if (future != null) {
future.cancel(mayInterruptIfRunning);
}
}
/**
* Trigger cancellation of this scheduled task with forced interruption if running.
*/
public void cancel() {
this.cancel(true);
}
Thanks