How to check if the executor service is shut down

Overview

The isShutdown method of ExecutorService in Java is used to check if the executor service is shut down or not.

Syntax

boolean isShutdown();

Parameters

This method has no parameters.

Return value

This method returns true if the executor service is shut down. Otherwise, returns false.

Code

Let’s look at the code below:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws InterruptedException {
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.submit(() -> System.out.println("Hello Educative"));
if(!singleThreadExecutor.isShutdown()){
singleThreadExecutor.shutdown();
singleThreadExecutor.awaitTermination(1, TimeUnit.SECONDS);
}
System.out.println("Executor service shut down - " + singleThreadExecutor.isShutdown());
}
}

Explanation

  • Lines 1 to 3: We import the relevant classes.
  • Line 8: We call a single-threaded executor service, and define singleThreadExecutor.
  • Line 9: We submit a task to the singleThreadExecutor that prints a string.
  • Lines 10 to 13: We check whether the singleThreadExecutor shuts down. If it’s not shut down yet, the shutdown method is invoked on the service. Finally, we wait for the termination of the service for one second using the awaitTermination method.
  • Line 14: We again check if the service is shut down.

Free Resources