Java - Quick Tips & Tutorials #1

Ömer Kurular
2 min readDec 18, 2021

--

In this series, I will write short tutorials and tips for Java environment including Spring Boot, Spring Cloud, microservices, testing. First one will be about terminating executor services.

Shutting down executor service gracefully

Executor services are important part of multi-threaded applications. They let you easily execute your tasks concurrently with a thread pool it maintains. In this article, I am not going talk about basics of executor services but an important thing about them. When you are done with an executor service, you better shut it down to release resource it uses. Below you will see how you can do that in a graceful manner.

If you are no longer in need of the executor service, first you should send shutdown command. This will let executor service know that it cannot accept tasks anymore. But, this does not mean that it is now shutdowned. It will still wait for existing tasks to complete.

Now, we can wait for tasks to complete for an amout of time of our choice. If tasks are not completed in that given duration, we won’t call shutdownNow method. This will set interrupted flags of threads true. Remember that, this interruption mechanism still depends on your thread implementation logic. When your thread gets interruption signal, your thread logic should be in shape to answer the interruption like breaking a loop.

ExecutorService executorService = Executors.newCachedThreadPool();
// use your executor
// ...

// shutdown if you are done with it
executorService.shutdown(); // --> let executor know that it will no longer accept new tasks

try {
if (!executorService.awaitTermination(1, TimeUnit.SECONDS)) {
executorService.shutdownNow(); // --> sends interrupt signal to all threads
}
} catch (InterruptedException e) {
// current thread may get interrupted waiting termination,
// in this case, we should send interrupt to running threads
executorService.shutdownNow();
Thread.currentThread().interrupt();
}

One more note, you should also carefully decide when to shutdown the executor service as constantly starting and shutting down the executor service may come costly. In your spring application, you can use this termination logic in PreDestroy phase of a bean.

https://github.com/kurular4/medium-shorts

--

--

Ömer Kurular

I am Ömer and currently working as a full-time software engineer. I will share my knowledge with you I gained through years of professional and self working.