Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I do first - cancel ScheduledFuture or shutdown ScheduledExecutorService?

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?

like image 312
yegor256 Avatar asked May 24 '12 12:05

yegor256


1 Answers

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.

like image 89
Erick Robertson Avatar answered Oct 20 '22 16:10

Erick Robertson