shutdown(): Initiating Orderly Termination
What you'll learn: How the shutdown() method allows an executor to complete all submitted tasks while refusing new ones.
The Concept of Orderly Termination
When you call shutdown() on an ExecutorService, you're telling it: "No more tasks, please—but finish what you've already started." This is the polite, graceful way to wind down a thread pool.
Think of it like a restaurant closing for the night: shutdown() is equivalent to locking the front door (no new customers) while letting everyone already seated finish their meals. The kitchen completes existing orders, but takes nothing new.
How shutdown() Works
The shutdown() method initiates an orderly shutdown where:
- Previously submitted tasks continue to execute — anything already in the queue or currently running will complete normally
- New task submissions are rejected — calling
execute()orsubmit()after shutdown throwsRejectedExecutionException - The method returns immediately — it doesn't wait for tasks to finish; it just changes the executor's state
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> System.out.println("Task 1"));
executor.submit(() -> System.out.println("Task 2"));
executor.shutdown(); // Initiates orderly shutdown
// These tasks will still execute:
// - Task 1 and Task 2 will complete normally
// This would throw RejectedExecutionException:
// executor.submit(() -> System.out.println("Task 3"));
Non-Blocking Nature
Unlike awaitTermination(), shutdown() doesn't block. It simply updates the executor's internal state and returns immediately. You typically combine it with awaitTermination() or isTerminated() if you need to wait for actual completion.
Key Takeaway: shutdown() prevents new task submissions while guaranteeing that all previously submitted tasks will execute to completion—it's the first step in gracefully terminating an executor service.