Home > Back-end >  ScheduledThreadPoolExecutor doesn’t terminate after the web application is closed
ScheduledThreadPoolExecutor doesn’t terminate after the web application is closed

Time:09-17

In my Java web application, I am using a ScheduledThreadPoolExecutor to periodically check the database connection status.

final ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
       
Runnable task = new Runnable() {
     public void run() {
          //check the status of the database connection, and log the result
     }
};

        
executor.scheduleWithFixedDelay(task, 0, 10, TimeUnit.MINUTES);

However, when I logout from the web application, and close the browser window, I see (from the logs) that it is still checking for connection status.

Is there any way to terminate this executor/thread upon closing the web application?

CodePudding user response:

I'm not sure to have fully understood the question, but in the section for exiting from the application, you probably should do the following

executor.shutdown();
    try { executor.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { }

Hoping it'll help

CodePudding user response:

Thread pool lives on

The thread pool of an executor service may continue running after its parent app has ended. This includes web apps.

So you should always do a graceful shutdown of the executor when exiting the app. Otherwise the backing thread(s) may continue running indefinitely, like a zombie

  • Related