简体   繁体   中英

Stop Spring Boot on thread error

I have this configuration using Spring Boot:

@Bean
public TaskExecutor a() {
  return new SimpleAsyncTaskExecutor();
}

@Bean
public CommandLineRunner b() {
  return (String... args) -> {
    RunnableTask task = SomeRunnableTask();
    a().execute(task);
  };
}

When that thread stops (for any reason) I want to shut down the Spring Boot application.

The thread is a long running process connecting to a database, webservice, socket... So it's quite likely that at some point it'll fail.

What's the right way of shutting down Spring Boot when a thread stops? Should I not be using SimpleAsyncTaskExecutor from Spring?

Thanks!

Spring Boot has a ShutdownEndpoint which

Allows the application to be gracefully shutdown (not enabled by default).

You have to take a look on it:

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(500L); // For the response to be sent back to the requester
        }
        catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        ShutdownEndpoint.this.context.close();  // The ConfigurableApplicationContext 
    }
});
thread.setContextClassLoader(getClass().getClassLoader());
thread.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM