ThreadPoolTaskExecutor graceful shutdown

I'm using the Spring (v4) ThreadPoolTaskExecutor to execute some continuous runnable tasks. When the application shuts down, I want a graceful shutdown of the executor so that tasks have some time to complete their iteration before continuing the shutdown. If an active task completes its iteration prior to the executors wait time expiring (e.g. ThreadPoolTaskExecutor.setAwaitTerminationSeconds()), I do not want it to start another iteration. So far I have not been able to accomplish this. I have the following executor configuration:

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(30);

And my tasks are essentially setup as such:

 myExecutor.execute(() -> { while(true) { doSomething(); } });

I assume I need to set a flag in my thread when the executor shuts down so that the loop breaks. Is there another recommended approach?

1 Answer

Your run method is a endless loop, so you don't need to

executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(30);

After removing above code, when you shutdown the thread pool, your working thread will be marked as iterrupted immediatly, but they will continue their work(unless they are sleeping, or InterruptionException will be thrown), and tasks in the cache queue will not be executed. You can just check this state and do not start next iteration.

myExecutor.execute(() -> { while(true && !Thread.currentThread().isInterrupted()) { doSomething(); }
});
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like