Spring webapp - closing threads when an application stops

I create a ScheduledExecutorService using the Spring ApplicationListener interface as follows:

@Component
public class ExecutorsStart implements ApplicationListener<ContextRefreshedEvent> {

    private ScheduledExecutorService executor;

@Autowired
Scheduler scheduler;

@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
    executor = Executors.newSingleThreadScheduledExecutor();
    scheduler.init();
    int delay = 10;
    int period = 60;// repeat every 1 minutes.
    executor.scheduleAtFixedRate(scheduler, delay, period, TimeUnit.SECONDS);
}

At the moment, Tomcat will not close when I start. /shutdown.sh, with the message:

The web application [/foo] appears to have started a thread named [pool-1-thread-1] but has failed to stop it

and it looks like I haven't written code yet to stop the ScheduledExecutorService.

My question is: how should this be done correctly in this environment?

I noticed that there is a ContextStoppedEvent , so I implemented a listener for it:

@Component
public class ExecutorsStop implements ApplicationListener<ContextStoppedEvent> {

@Autowired
ExecutorsStart executorsStart;

@Override
public void onApplicationEvent(final ContextStoppedEvent event) {
    executorsStart.executor.shutdownNow();
}

But it seems that this event handler is not called when Tomcat disconnects.

Am I doing it wrong, or am I going through it completely?

+4
source share
1 answer

ContextClosedEvent.

@Component
public class ExecutorsStop implements ApplicationListener<ContextClosedEvent> {

    @Autowired
    ExecutorsStart executorsStart;

    @Override
    public void onApplicationEvent(final ContextClosedEvent event) {
        System.out.println("Stopped: " + event);
    }
}

, contextDestroyed(..) ServletContextListener destroy() Servlet. ContextLoaderListener DispatcherServlet close() ApplicationContext.

+6

Source: https://habr.com/ru/post/1533453/


All Articles