What is the awaitTermination method of executor service in Java?
The awaitTermination method
The awaitTermination method of ExecutorService in Java
is used to wait for all the tasks submitted to the service to complete execution:
- After the shutdown of the service was initiated
- The wait time for the termination of the service is over
- The current thread of execution is interrupted
The method takes a timeout parameter that indicates the maximum time to wait for all the tasks submitted to finish.
Syntax
boolean awaitTermination(long timeout, TimeUnit unit)
Parameters
long timeout: This is the maximum time to wait.TimeUnit unit: This is the unit of time of the timeout argument.
Return value
This method returns true if the executor service was terminated or returns false if the wait time elapsed before termination.
Code
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.");}}}
Explanation
- Lines 1 to 3: We import the relevant classes.
- Line 8: We define a single-threaded executor service called
singleThreadExecutor. - Line 9: We submit a task to the
singleThreadExecutorthat prints a string. - Lines 10-15: 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. Depending on the value returned by theawaitTerminationmethod, we print whether the service termination was successful or unsuccessful.