Course contentsShow
← Java
Lesson 2773 of 2,87050. Executor FrameworkFree lesson

awaitTermination(): Waiting for Shutdown Completion

Learn to use awaitTermination() to block until all tasks finish after shutdown() or shutdownNow().

awaitTermination(): Waiting for Shutdown Completion

You'll learn how to block your application until all submitted tasks finish executing after an executor shutdown.

The Problem: Shutdown Isn't Instant

When you call shutdown() or shutdownNow(), the executor immediately enters a shutdown state, but tasks don't magically stop running. Previously submitted tasks may still be executing. How do you know when the executor has actually finished all work?

What awaitTermination() Does

The awaitTermination(long timeout, TimeUnit unit) method blocks the calling thread until one of three things happens:

  1. All tasks complete after shutdown was initiated
  2. The timeout expires before completion
  3. The current thread is interrupted

Think of it like waiting at a restaurant after closing time. You've announced "we're closing" (shutdown()), but customers are still finishing their meals. awaitTermination() is you sitting by the door, waiting for the last customer to leave—but only for a certain amount of time.

Return Value

The method returns a boolean:

  • true if the executor terminated completely
  • false if the timeout elapsed before termination

Typical Pattern

ExecutorService executor = Executors.newFixedThreadPool(4);

// Submit tasks...
executor.submit(() -> { /* work */ });

executor.shutdown(); // Initiate shutdown

try {
    if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        // Timeout occurred, force shutdown
        executor.shutdownNow();
    }
} catch (InterruptedException e) {
    executor.shutdownNow();
    Thread.currentThread().interrupt();
}

This ensures your application waits for graceful completion but doesn't hang forever.

Key Takeaway: awaitTermination() blocks until all tasks finish after shutdown, with a configurable timeout to prevent indefinite waiting—essential for clean application shutdown.