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

shutdownNow(): Forcing Immediate Termination

Learn how shutdownNow() attempts to stop all actively executing tasks and returns unexecuted tasks.

shutdownNow(): Forcing Immediate Termination

You'll learn how shutdownNow() forcefully stops an executor by attempting to halt running tasks and returning those that never started.

The Nuclear Option for Shutdown

While shutdown() is polite and waits for queued tasks to finish, shutdownNow() is the emergency stop button. When you call this method, the executor framework attempts to stop all actively executing tasks immediately and prevents any queued tasks from starting. It's like pulling the fire alarm during a meeting—everyone stops what they're doing.

What shutdownNow() Does

When invoked, shutdownNow() performs three actions:

  1. Prevents new task submissions (just like shutdown())
  2. Attempts to stop all actively executing tasks by interrupting their threads
  3. Returns a list of tasks that were queued but never started

The key word is "attempts"—there's no guarantee running tasks will stop instantly. They must respond to interruption properly (checking Thread.interrupted() or handling InterruptedException).

The Return Value Matters

List<Runnable> neverRan = executor.shutdownNow();
System.out.println("Tasks that never executed: " + neverRan.size());

Unlike shutdown() which returns void, shutdownNow() returns a List<Runnable> containing all tasks that were sitting in the queue waiting to be executed. This gives you a chance to handle them—perhaps logging what was skipped or rescheduling them elsewhere.

When to Use It

Use shutdownNow() when you need to terminate quickly due to critical errors, application shutdown sequences, or timeout scenarios where waiting for graceful completion isn't acceptable.

Key Takeaway: shutdownNow() attempts immediate termination by interrupting running tasks and returns all queued-but-unexecuted tasks as a list—use it when graceful shutdown isn't fast enough.