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
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.