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

awaitTermination: Blocking Until Shutdown Completes

How awaitTermination(timeout, unit) blocks the calling thread until all tasks finish or the timeout expires.

awaitTermination: Blocking Until Shutdown Completes

You'll learn how to make your program wait for all executor tasks to complete or timeout.

The Problem: Uncertain Shutdown Timing

When you call shutdown() or shutdownNow() on an ExecutorService, those methods return immediately—they don't wait for running tasks to finish. Your main thread might continue executing (or even exit) while worker threads are still processing tasks. How do you wait until the executor truly finishes?

The awaitTermination Method

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

  1. All tasks complete after a shutdown request
  2. The timeout expires (whichever comes first)
  3. The current thread is interrupted

The method returns true if the executor terminated, false if the timeout elapsed first.

Why This Matters

Think of awaitTermination like waiting at a restaurant after closing time. You've told the kitchen "no more orders" (shutdown()), but you want to wait until the chef finishes cooking the last meals before locking up. You'll wait up to 30 minutes—if they're done sooner, great! If not, you'll leave anyway.

Typical Pattern

After calling shutdown(), immediately call awaitTermination() to pause your program until workers finish:

executor.shutdown();
boolean finished = executor.awaitTermination(1, TimeUnit.MINUTES);
if (finished) {
    // All tasks completed successfully
} else {
    // Timeout expired, some tasks may still be running
}

This gives you precise control over shutdown timing without busy-waiting or guessing.

Key Takeaway: awaitTermination blocks the calling thread until all executor tasks complete or a timeout expires, enabling graceful and predictable shutdown sequences.