Future 与错误处理
使用 Future.get 设置超时,处理 ExecutionException,并取消正在运行的任务
Future 与错误处理 是 CoddyKit 上的免费 Java Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Java Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Java Academy 课程共包含 4 节课。
什么是 Future
Future<V> 表示异步计算尚未完成的结果。它提供了检查完成状态、等待结果以及处理错误的方法。
import java.util.concurrent.*;
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<Integer> future = pool.submit(() -> {
Thread.sleep(1000);
return 42;
});
System.out.println("Is done? " + future.isDone()); // false
Integer result = future.get(); // blocks
System.out.println("Result: " + result); // 42
pool.shutdown();带超时的 future.get()
请始终优先使用带超时的变体,以避免无限期挂起:
try {
Integer result = future.get(5, TimeUnit.SECONDS);
System.out.println(result);
} catch (TimeoutException e) {
System.out.println("Timed out");
future.cancel(true); // interrupt the task
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
System.out.println("Task threw: " + e.getCause());
}ExecutionException
如果任务抛出了异常,future.get() 会将其包装在 ExecutionException 中。请使用 getCause() 解包:
Future<String> failing = pool.submit(() -> {
throw new IllegalArgumentException("bad input");
});
try {
failing.get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
System.out.println(cause.getClass().getSimpleName()); // IllegalArgumentException
System.out.println(cause.getMessage()); // bad input
}取消 Future
cancel(mayInterruptIfRunning) 会尝试取消任务。成功时返回 true。如果 mayInterruptIfRunning 为 true,则会向正在运行的线程发送中断信号。
Future<String> f = pool.submit(() -> {
try {
Thread.sleep(10_000); // long task
return "done";
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return "interrupted";
}
});
boolean cancelled = f.cancel(true); // send interrupt
System.out.println("Cancelled: " + cancelled); // true
System.out.println("Is cancelled: " + f.isCancelled()); // trueisCancelled 与 isDone
如果任务正常完成、抛出异常或被取消,isDone() 都会返回 true。只有任务被取消时,isCancelled() 才会返回 true。
// After cancel:
System.out.println(f.isDone()); // true
System.out.println(f.isCancelled()); // true
// After normal completion:
Future<Integer> done = pool.submit(() -> 5);
done.get(); // wait
System.out.println(done.isDone()); // true
System.out.println(done.isCancelled()); // falseCompletionService:获取第一个可用结果
ExecutorCompletionService 会包装一个线程池,并提供 take() 方法来获取下一个已完成的 Future(按照完成顺序,而不是提交顺序):
ExecutorCompletionService<Integer> cs =
new ExecutorCompletionService<>(pool);
for (int i = 0; i < 5; i++) {
final int delay = 5 - i; // submit fastest last
cs.submit(() -> { Thread.sleep(delay * 100); return delay; });
}
for (int i = 0; i < 5; i++) {
Future<Integer> f = cs.take(); // next completed
System.out.println(f.get());
}安全处理多个 Future
从多个 Future 收集结果时,请逐个遍历并分别处理每个 Future 的异常:
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < 5; i++) {
final int id = i;
futures.add(pool.submit(() ->
id % 2 == 0 ? "ok_" + id : (() -> { throw new RuntimeException("fail_"+id); }).get()
));
}
for (Future<String> f : futures) {
try {
System.out.println(f.get());
} catch (ExecutionException e) {
System.out.println("Error: " + e.getCause().getMessage());
}
}线程池关闭后的 Future.get()
在 shutdown() 之后提交任务会抛出 RejectedExecutionException。但是,在关闭之前提交的 Future 仍然可以在关闭后获取:
ExecutorService pool2 = Executors.newFixedThreadPool(2);
Future<Integer> f = pool2.submit(() -> 99);
pool2.shutdown(); // no new tasks
// Still valid — task was submitted before shutdown:
System.out.println(f.get()); // 99
try {
pool2.submit(() -> 0); // throws!
} catch (RejectedExecutionException e) {
System.out.println("Pool shut down");
}FutureTask:手动创建 Future
FutureTask<V> 同时实现了 Runnable 和 Future<V>,适用于不使用 ExecutorService 但需要 Future 的情况:
FutureTask<String> task = new FutureTask<>(() -> "computed");
new Thread(task).start(); // run in any thread
System.out.println(task.get()); // computed使用 Future 实现重试模式
围绕 future.get() 实现简单的重试逻辑:
Future<String> future = pool.submit(() -> {
if (Math.random() < 0.7) throw new RuntimeException("transient error");
return "success";
});
for (int attempt = 0; attempt < 3; attempt++) {
try {
System.out.println(future.get());
break;
} catch (ExecutionException e) {
System.out.println("Attempt " + (attempt+1) + " failed");
if (attempt == 2) throw e;
future = pool.submit(() -> "retry"); // resubmit
}
}Future 的限制
java.util.concurrent.Future 存在以下限制:
- 没有回调——必须使用 get() 阻塞等待
- 无法串联转换操作
- 无法组合多个 Future
对于响应式、非阻塞式组合,请使用 CompletableFuture(下一门课程)。
快速检查
一个任务抛出了异常。调用 future.get() 时会抛出什么异常?
回顾:Future 与错误处理
要点:
- future.get() 会阻塞;务必使用带超时的变体
- ExecutionException 会包装任务异常;使用 getCause() 解包
- cancel(true) 会发送中断信号;使用 isDone/isCancelled 检查状态
- ExecutorCompletionService.take() 按完成顺序获取 Future
- FutureTask 同时实现 Runnable 和 Future
常见问题解答
「Future 与错误处理」课时是免费的吗?
是的 — 「Future 与错误处理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Java Academy 课程的其余内容,请升级到 CoddyKit PRO。 Java Academy 课程共包含 4 节课。
「Future 与错误处理」这节课中我会学到什么?
使用 Future.get 设置超时,处理 ExecutionException,并取消正在运行的任务 你通过在浏览器中直接运行的动手代码来练习 Java Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Java Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Java Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「Future 与错误处理」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Java Academy 课中编写并运行代码吗?
能。每节 Java Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。