The isTerminated
method of the ExecutorService
in Java is used to check whether the executor service is terminated or not.
boolean isTerminated();
This method has no parameters.
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.
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()); } }
Lines 1 to 3: We import the relevant classes.
Line 8: We call a single-threaded executor service, and singleThreadExecutor
is defined.
Line 9: We submit a task to the singleThreadExecutor
that prints a string.
Lines 10 to 13: We check whether the singleThreadExecutor
is terminated. If it’s not yet terminated, 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 terminated.
RELATED TAGS
CONTRIBUTOR
View all Courses