awaitTermination
methodThe awaitTermination
method of ExecutorService
in Java
is used to wait for all the tasks submitted to the service to complete execution:
The method takes a timeout parameter that indicates the maximum time to wait for all the tasks submitted to finish.
boolean awaitTermination(long timeout, TimeUnit unit)
long timeout
: This is the maximum time to wait.TimeUnit unit
: This is the unit of time of the timeout argument.This method returns true
if the executor service was terminated or returns false
if the wait time elapsed before termination.
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();if(singleThreadExecutor.awaitTermination(1, TimeUnit.SECONDS)) System.out.println("Executor service terminated successfully.");else System.out.println("Executor service termination unsuccessful.");}}}
singleThreadExecutor
.singleThreadExecutor
that prints a string.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. Depending on the value returned by the awaitTermination
method, we print whether the service termination was successful or unsuccessful.