RejectedExecutionException After Shutdown
What you'll learn: How to handle the exception that occurs when tasks are submitted to a shutdown executor.
The Problem: No New Work After Closing Time
Once you call shutdown() or shutdownNow() on an ExecutorService, the executor enters a state where it won't accept new tasks. If you try to submit a task after shutdown, Java throws a RejectedExecutionException.
Think of it like a restaurant kitchen after closing time. Once the chef announces "we're closed," any new orders placed will be rejected—the kitchen simply won't accept them.
When This Exception Occurs
The RejectedExecutionException (an unchecked RuntimeException) is thrown by:
execute(Runnable)submit(Runnable)orsubmit(Callable)invokeAll(Collection<Callable>)invokeAny(Collection<Callable>)
This happens when:
- The executor has been shut down via
shutdown()orshutdownNow() - You attempt to submit a new task afterward
Handling the Exception
You have two main approaches:
Check before submitting:
if (!executor.isShutdown()) {
executor.submit(task);
} else {
// Handle rejection gracefully
}
Catch the exception:
try {
executor.submit(task);
} catch (RejectedExecutionException e) {
// Executor is shut down, handle appropriately
System.err.println("Cannot submit task: executor shut down");
}
The check-first approach prevents the exception but has a race condition (executor could shut down between check and submit). The catch approach is more robust for concurrent scenarios.
Key Takeaway: After calling shutdown() or shutdownNow(), any attempt to submit new tasks throws RejectedExecutionException. Always either check isShutdown() before submitting or catch the exception to handle graceful degradation.