How to check if the executor service is terminated
Overview
The isTerminated method of the ExecutorService in Java is used to check whether the executor service is terminated or not.
Syntax
boolean isTerminated();
Parameters
This method has no parameters.
Return value
This method returns true if the executor service is terminated. Otherwise, returns false. The method returns true only after the shutdown or shutdownNow methods are called.
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.isTerminated()){singleThreadExecutor.shutdown();singleThreadExecutor.awaitTermination(1, TimeUnit.SECONDS);}System.out.println("Executor service terminated - " + singleThreadExecutor.isTerminated());}}
Explanation
-
Lines 1 to 3: We import the relevant classes.
-
Line 8: We call a single-threaded executor service, and
singleThreadExecutoris defined. -
Line 9: We submit a task to the
singleThreadExecutorthat prints a string. -
Lines 10 to 13: We check whether the
singleThreadExecutoris terminated. If it’s not yet terminated, theshutdownmethod is invoked on the service. Finally, we wait for the termination of the service for one second using theawaitTerminationmethod. -
Line 14: We again check if the service is terminated.