My code:
ScheduledServiceExecutor service = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture future = service.scheduleWithFixedDelay(
runnable, 1, 1, TimeUnit.MILLISECONDS
);
// ...
// now it's time to shut it all down
future.cancel(true);
service.shutdown();
Am I right here? Maybe I should do:
service.shutdown();
future.cancel(true);
What do you think?
In this case, you only need the call to shutdown()
.
There are two options in the ScheduledThreadPoolExecutor
, which is what is being created behind the scenes here. getExecuteExistingDelayedTasksAfterShutdownPolicy()
defaults to true
and getContinueExecutingPeriodicTasksAfterShutdownPolicy()
defaults to false
. So, simply shutting down the service will cause periodic tasks to be canceled, but any delayed tasks will still be executed. Since the task in question is a periodic task, it will be canceled upon shutdown.
My personal opinion is that it's better to call the .cancel(true)
manually before shutdown. While operationally this has no different effect, I think it's good for programmers who may not know the options on the executor to see that the periodic task is meant to be canceled upon shutdown. This also means that if anyone ever comes in and changes the executor to one which doesn't cancel upon shutdown, this task will still be canceled. So really, I think the main benefit here is clarity of code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With