ExecutorService does not close from contextDestroyed () when Tomcat stops

I have ExecutorService executor = Executors.newSingleThreadExecutor();one that I want to stop when the server shuts down.

I have a class that implements ServletContextListener, and it is annotated using @WebListener.

I have two methods in this class:

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    System.out.println("ServletContextListener started");
}

@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    executor.shutdown();
    executor.shutdownNow();
    System.out.println("ServletContextListener destroyed");
}

And I see that it prints what is in both of them, when it should have been, but when I press the stop button once in intelij, I get:

SEVERE: The web application [] seems to have started a thread named [pool-2-thread-1], but did not stop it. This will likely lead to a memory leak.

Immediately after printing ServletContextListener destroyed.

I need to press the stop button again to completely stop it.

Why doesn't it disable the ExecutorService even if it has reached executor.shutdown();? What am I doing wrong?

PS: ExecutorService, , .

EDIT2:

- - , :

private ExecutorService executor = Executors.newSingleThreadExecutor();

( ):

public static RoomsManager getRoomsManager(ServletContext servletContext) {
    if (servletContext.getAttribute(MANAGER_GAMES_ATTRIBUTE_NAME) == null) {
        servletContext.setAttribute(MANAGER_GAMES_ATTRIBUTE_NAME, new RoomsManager());
    }
    return (RoomsManager)servletContext.getAttribute(MANAGER_GAMES_ATTRIBUTE_NAME);
}

:

@WebListener
public class RoomsManager  implements ServletContextListener {

- intelij IDEA.

+4
2

, RoomsManager (, , ): Tomcat, .

RoomsManager @WebListener, Tomcat , / . , ServletContextListener destroyed.

getRoomsManager (, ). Tomcat "" , .

+2

:

class YourThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable r) {
        return new Thread(r, "Your name");
    }
}
private ExecutorService executor = Executors.newSingleThreadExecutor(new YourThreadFactory());

, -, tomcat , , return new Thread(r, "Your name");, .

DefaultThreadFactory, -, , .

, executor.shutdown(); , , , .

+1

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


All Articles