How to abruptly shut down an executor service

How to shut down an executor service

The shutdownNow() method is used to shut down the executor service abruptly. This method tries to stop all jobs that are now running, pauses the processing of tasks that are waiting to be executed, and delivers a list of the tasks that were waiting.

Syntax


List<Runnable> shutdownNow()

Parameters

The method takes no parameters.

Return value

This method returns a list of jobs that were awaiting execution.

Example

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Main{
public static void main(String[] args) {
final ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
threadPool.execute(() -> {
if (threadPool.isShutdown()) {
System.out.println("Pool is terminating.");
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.println("WARN: Task interrupted");
}
System.out.println("Doing work.");
});
}
final List<Runnable> awaitingTasks = threadPool.shutdownNow();
System.out.println("The list of awaiting tasks are:" + awaitingTasks);
}
}

Explanation

  • Lines 1–4: We import the relevant classes.
  • Line 9: We create a fixed thread pool with 10 threads.
  • Line 11–23: In a for loop, we submit runnables to the thread pool. The runnable does the following:
    • It checks if the thread pool is shut down. If yes, we print Pool is terminating.
    • The current thread that executes the runnable is put to sleep. If the thread is interrupted, a warning is printed saying WARN: Task interrupted.
    • If none of the above two situations are reached, Doing work. is printed to indicate that the task/runnable is executing.
  • Line 25: We invoke the shutdownNow() method on the executor service or thread pool. The tasks awaiting execution are stored in the awaitingTasks list.
  • Line 26: We print the awaitingTasks list.