3

I have a spring boot java application that I'm trying to make gracefully shutdown. I'm using the shutdown endpoint.

My application is receiving WebSocket connections. When there is no connection yet the application shutdown correctly, but as soon as the first connection happens the shutdown will get stuck because the thread created by the connection is not affected by the graceful shutdown.

The way I catch the shutdown of the application is with ContextClosedEvent

like this :

@Override
    @EventListener
    public void onApplicationEvent(final ContextClosedEvent event) {
        connector.pause();
        Executor executor = this.connector.getProtocolHandler().getExecutor();
        if (executor instanceof ThreadPoolExecutor) {
            try {
                ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;

                threadPoolExecutor.shutdown();
                if (!threadPoolExecutor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {

                    threadPoolExecutor.shutdownNow();

                    if (!threadPoolExecutor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
                        logger.error("Tomcat thread pool did not terminate");
                    }
                }
            } catch (InterruptedException  ex)  {
                Thread.currentThread().interrupt();
            }
        }

And my thread are created like this :

private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);

private void foo(String bar) {
        Runnable runnable = new Runnable()

        ScheduledFuture<?> future = executorService.schedule(runnable, sessionTimeout, TimeUnit.SECONDS);
        sessionFutures.put(sessionId, future);
    }

The thread that is created and that is not affected by threadPoolExecutor.shutdown() or .shutdownNow() is Name and description of the thread

My question is why this thread isn't shut down and how can I make it shutdown?

My hypothesis is that i don't associate the task I'm creating to the current executor that is running.

  • i know this does not answer your question, but here is an alternate method for shutdown, did you try: https://stackoverflow.com/questions/26547532/how-to-shutdown-a-spring-boot-application-in-a-correct-way – sudipn Dec 10 '19 at 15:42
  • Yes, I chose the shutdown endpoint because I can use it with the preStop hook of a Kubernetes deployment – Marc-Antoine Caron Dec 10 '19 at 15:52
  • When you create the threads, how is the behavior if you replace your own instance of `ScheduledExecutorService` with the [TaskScheduler](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/TaskScheduler.html) from Spring? – sudipn Dec 10 '19 at 16:10
  • Now yes and it isn't working either – Marc-Antoine Caron Dec 10 '19 at 19:03

0 Answers0