Sub topic 9
What Happens When a Task Throws
Code inside a task can fail, like any other code. A number might not parse, a file might be missing, or a value might be null. In a normal program, an exception moves up the call stack until something catches it. A task in an ExecutorService runs on a different thread, so the exception cannot move up into the code that submitted the task. This chapter shows where that exception goes and how you get it back.
Why a Task's Exception Cannot Reach You Directly
The call stack is the chain of method calls that led to the current line of code. Each thread has its own call stack. When you call pool.submit(task), your thread hands the task to the pool and moves on. Later, a worker thread runs the task on the worker's own call stack.
If the task throws, the exception moves up the worker's stack. Your code is not on that stack, so your try/catch around submit never sees it. By the time the task fails, your thread may be doing something else entirely.
The pool has to store the exception somewhere until you ask for it. That storage place is the Future.
The Future Keeps the Exception for You
A Future holds the outcome of a task. The outcome is one of two things:
- a normal result, if the task finished without problems
- an exception, if the task threw
When you call get(), the Future gives you the outcome. If the outcome is a result, get() returns it. If the outcome is an exception, get() throws an ExecutionException. This is a checked exception from java.util.concurrent that wraps the original exception. Wrapping means one exception carries another inside it. You reach the original with getCause().
A Worked Example: Parsing Bad Input
This program submits a task that tries to turn the text "not a number" into an int. That fails with a NumberFormatException.
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TaskFailureDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Callable<Integer> failing = () -> Integer.parseInt("not a number");
Future<Integer> result = pool.submit(failing);
result.get();
} catch (ExecutionException e) {
System.out.println("Task failed: " + e.getCause());
} finally {
pool.shutdown();
}
}
}Output:
Task failed: java.lang.NumberFormatException: For input string: "not a number"Here is what happens, step by step:
submitreturns aFutureright away. No exception yet.- The worker thread runs the task, and
parseIntthrows. - The pool catches the exception and stores it in the
Future. result.get()throws anExecutionException.- The
catchblock callsgetCause()and prints the originalNumberFormatException.
The finally block shuts the pool down whether or not the task failed. The throws InterruptedException on main is there because get() can also throw InterruptedException if your thread is interrupted while it waits.
The Silent Failure Trap
The pool only shows you the stored exception when you call get(). If you never call get(), you never see it. Nothing prints and nothing crashes. The task just stops partway through.
This catches beginners most often with submit on a task that returns nothing. Since there is no result to read, it is easy to throw the Future away.
The other way to give a pool a task is execute. It takes a Runnable and returns nothing, not even a Future. Because there is no Future to hold the exception, the exception reaches the worker thread's uncaught exception handler. This is the code a thread runs when an exception escapes it. By default, the handler prints the stack trace to the error output.
This program runs both methods side by side:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SilentFailureDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.submit(() -> {
System.out.println("submit: about to fail");
throw new IllegalStateException("lost with submit");
});
pool.execute(() -> {
System.out.println("execute: about to fail");
throw new IllegalStateException("printed with execute");
});
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
}
}Typical output:
submit: about to fail
execute: about to fail
Exception in thread "pool-1-thread-1" java.lang.IllegalStateException: printed with execute
at SilentFailureDemo.lambda$main$1(SilentFailureDemo.java:13)
...The message "lost with submit" never appears. That task failed silently.
| How you hand over the task | What you get back | Where the exception goes | Do you see it? |
|---|---|---|---|
| `submit(Callable)` | `Future<T>` | Stored in the `Future` | Only when you call `get()` |
| `submit(Runnable)` | `Future<?>` | Stored in the `Future` | Only when you call `get()` |
| `execute(Runnable)` | nothing | Uncaught exception handler | Yes, printed by default |
Checked Exceptions: Callable Versus Runnable
A checked exception is one the compiler makes you handle or declare, such as IOException. The two task types treat checked exceptions differently:
Runnable.run()declares no exceptions. ARunnablelambda cannot throw a checked exception. You must catch it inside the task.Callable.call()is declaredthrows Exception. ACallablelambda may throw any checked exception, and the pool wraps it in anExecutionExceptionlike any other.
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CheckedExceptionDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Callable<String> readConfig = () -> {
throw new IOException("config file missing");
};
Future<String> config = pool.submit(readConfig);
config.get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException) {
System.out.println("I/O problem: " + cause.getMessage());
} else {
System.out.println("Other problem: " + cause);
}
} finally {
pool.shutdown();
}
}
}Output:
I/O problem: config file missingThe instanceof check lets you react differently to different kinds of failure. getCause() returns a Throwable, so you check its type before treating it as an IOException.
Handling Failures One Task at a Time
When you submit several tasks, one failure should not hide the others' results. Put the try/catch around each get() call, inside the loop, rather than around the whole loop.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ManyResultsDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
List<Future<Integer>> results = new ArrayList<>();
for (String text : List.of("10", "oops", "32")) {
results.add(pool.submit(() -> Integer.parseInt(text)));
}
int total = 0;
for (Future<Integer> f : results) {
try {
total += f.get();
} catch (ExecutionException e) {
System.out.println("Skipped: " + e.getCause().getMessage());
}
}
System.out.println("Total: " + total);
} finally {
pool.shutdown();
}
}
}Output:
Skipped: For input string: "oops"
Total: 42The bad input is reported, and the two good results still add up to 42. If the try/catch were outside the loop, the first failure would end the loop, and you could lose the result for "32".
A Failing Task Does Not Break the Pool
One failed task does not stop the pool. With submit, the worker thread catches the exception, stores it, and moves on to the next task. With execute, the exception ends that worker thread, and the pool starts a new worker to take its place. In both cases the pool keeps accepting and running tasks. You still have to shut it down yourself, as the earlier chapter on shutdown showed.
Common Mistakes
- Printing
einstead ofe.getCause(). The message then describes theExecutionExceptionwrapper instead of the real problem. - Wrapping
submit(...)intry/catchand expecting the task's exception there.submititself does not throw the task's exception. - Throwing away the
Futurereturned bysubmit, which hides every failure. - Catching
ExecutionExceptionbut forgetting thatget()can also throwInterruptedException.
Exercise
A program calls pool.submit(() -> { throw new RuntimeException("boom"); }); and never stores the returned Future. What does the user see when the task runs?
Show answer
Nothing. The exception is stored in the discarded Future, and since get() is never called, it is never thrown or printed. The task fails silently.
Exercise
You catch an ExecutionException from future.get(). Which method gives you the exception the task actually threw, and what type does that method return?
Show answer
e.getCause() returns the original exception. Its declared return type is Throwable, so use instanceof to check the specific type before casting it.
Exercise
Why can a Callable lambda throw an IOException while a Runnable lambda cannot?
Show answer
Callable.call() is declared with "throws Exception", so it may throw checked exceptions. Runnable.run() declares no exceptions, so any checked exception must be caught inside the Runnable.
Exercise
You submit five tasks and loop over their Futures with a single try/catch around the whole loop. The second task fails. What goes wrong, and how do you fix it?
Show answer
The ExecutionException from the second get() jumps out of the loop, so results from tasks three to five are never read. Move the try/catch inside the loop, around each get() call, so every Future is checked.