0

After thinking about how to run an infinite task in Spring Boot (see my previous question), I decided to do this:

@Component
@EnableAsync
public class MyRunner implements CommandLineRunner {

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Async
    @Override
    public void run(String... args) throws Exception {
        try {
            infiniteLoop();
        } finally {
            this.scheduledExecutorService.shutdown();
        }
    }
}

This allows the SpringApplication#run method to fully complete.

As part of the whole thing, I have declared a ScheduledExecutorService bean. My issue is that if infiniteLoop() throws an unexpected exception, the Executor will prevent the application from shunting down as it is managed externally.

Is there a better way to handle such a case? Or is this a good use of the finally block?

Community
  • 1
  • 1
Djon
  • 2,230
  • 14
  • 19
  • So you want that the boot application stops after unexpected exception, right? `shutdown` of the executerService wont accept new tasks but the already submitted tasks continue to run. Is this what you want? – Patrick Aug 04 '16 at 06:48
  • @Patrick Yes, without the executor everything just terminates, the context is destroyed and the application stops. But once the executor is started, it has to be manually `shutdown` at some point before the application can exit gracefully, and this is the solution I came up with. – Djon Aug 04 '16 at 08:01
  • 1
    From my point of view your solution is ok. Just want to share [this answer](http://stackoverflow.com/a/11520233/3493036) with you for optional implementation after shutdown call. – Patrick Aug 04 '16 at 08:06
  • @Patrick The tasks are actually really small and will always complete in a very short time, so calling `shutdown` or `shutdownNow` should be the same, but I'll have a look. – Djon Aug 04 '16 at 08:25

0 Answers0