Return Values: Handling Unexecuted Tasks
What you'll learn: How to work with the list of tasks returned by shutdownNow() that never got a chance to run.
The shutdownNow() Return Value
When you call shutdownNow() on an ExecutorService, it attempts to stop all actively executing tasks and returns something important: a List<Runnable> containing all the tasks that were queued but never started.
Think of it like a restaurant closing abruptly during dinner rush—some orders were being cooked (active tasks), but many order tickets were still waiting on the board. Those waiting tickets are what shutdownNow() hands back to you.
Why This Matters
These unexecuted tasks represent work that was submitted but lost when you forced shutdown. Depending on your application's needs, you might want to:
- Log them for auditing purposes
- Persist them to retry later
- Resubmit them to another executor
- Notify requesters that their work wasn't completed
Working with the Return Value
List<Runnable> unexecutedTasks = executor.shutdownNow();
if (!unexecutedTasks.isEmpty()) {
System.out.println("Warning: " + unexecutedTasks.size() + " tasks never ran");
// Option 1: Log them
for (Runnable task : unexecutedTasks) {
System.out.println("Unexecuted: " + task);
}
// Option 2: Submit to backup executor
ExecutorService backup = Executors.newSingleThreadExecutor();
unexecutedTasks.forEach(backup::execute);
}
Important Limitation
This list only contains tasks waiting in the queue. Tasks already executing when shutdownNow() was called won't appear here—those are interrupted but not returned.
Key Takeaway: Always check shutdownNow()'s return value to handle queued tasks that never executed, preventing silent data loss or incomplete operations.