Sub topic 3
What Happens When a Task Throws
This chapter covers what happens when a task fails. It then gives a quick tour of five more tools in the executor toolbox.
Errors Hide Inside the Future
An exception is an error object that Java throws when something goes wrong. If a task on a pool throws one, your code does not see it right away. The pool catches the error and stores it in the task's Future. When you call get(), Java throws an ExecutionException, which is a wrapper around the original error. Call getCause() to read the real problem.
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();
}
}
}More Executor Tools
| Tool | What it does |
|---|---|
| `invokeAll` | Runs a list of tasks and waits for all of them. It returns their Futures in the same order as the list. |
| `invokeAny` | Runs a list of tasks and returns the result of the first one that succeeds. |
| `ScheduledExecutorService` | Runs a task after a delay (`schedule`) or over and over (`scheduleAtFixedRate`). |
| `ThreadPoolExecutor` | Lets you set the core size, the maximum size, the work queue (the line of waiting tasks), and the rejection policy (what happens when the pool and queue are full). |
| `CompletableFuture` | Chains steps, such as `supplyAsync(...).thenApply(...)`, so each step starts when the one before it ends. |
| Virtual threads (Java 21+) | Very light threads. `Executors.newVirtualThreadPerTaskExecutor()` gives each task its own virtual thread. |
Here is a short CompletableFuture chain that runs on your own pool:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompletableFutureDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<String> result = CompletableFuture
.supplyAsync(() -> 21, pool)
.thenApply(n -> n * 2)
.thenApply(n -> "Answer: " + n);
System.out.println(result.join());
} finally {
pool.shutdown();
}
}
}Exercise
A task throws a NumberFormatException. What exception does Future.get() throw, and how do you get the original error?
Show answer
Future.get() throws an ExecutionException. Calling getCause() on it returns the original NumberFormatException.
Exercise
Which method runs a task every second: schedule or scheduleAtFixedRate?
Show answer
scheduleAtFixedRate. The schedule method runs a task only once, after a delay.