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

Graceful Shutdown: The shutdown Method

How shutdown() stops accepting new tasks while completing already-submitted tasks before terminating threads.

Graceful Shutdown: The shutdown Method

You'll learn how to politely tell an ExecutorService to finish its work and close down without abandoning running tasks.

The Core Idea

When you're done submitting tasks to an ExecutorService, you need a way to shut it down. The shutdown() method provides a graceful way to do this: it stops accepting new task submissions while allowing all previously-submitted tasks to complete before terminating the worker threads.

Think of it like a restaurant closing for the night. When the manager calls "last orders," new customers can't come in, but everyone already seated gets their meal and finishes dining. Only then do the staff go home.

How shutdown() Works

When you call shutdown() on an ExecutorService:

  1. New tasks are rejected — any subsequent execute() calls throw RejectedExecutionException
  2. Queued tasks continue — tasks waiting in the queue still get executed
  3. Running tasks finish — tasks currently being processed run to completion
  4. Threads terminate — only after all work is done do the pool threads exit
ExecutorService executor = Executors.newFixedThreadPool(3);

executor.execute(() -> System.out.println("Task 1"));
executor.execute(() -> System.out.println("Task 2"));

executor.shutdown(); // Signal: no more new tasks

// Task 3 would throw RejectedExecutionException
// executor.execute(() -> System.out.println("Task 3"));

// Tasks 1 and 2 will still complete

Why This Matters

Without calling shutdown(), your application won't terminate cleanly—the worker threads keep running, waiting for more work. Always shut down executors when you're done with them.

Key Takeaway: The shutdown() method gracefully stops an ExecutorService by rejecting new tasks while ensuring all submitted tasks complete before terminating threads.