实现说明
execute 与 submit 的异常命运不同以类 ExecutorSurvives为骨架。
IllegalStateException 在三处抛出,落脚点各不相同。第一处通过 execute() 提交,不在任何 try 里:异常逃出任务、到达 uncaughtExceptionHandler(打印 handler: boom),杀死工作线程,线程池随即补一个新线程,后续任务照常执行。第二处通过 submit() 提交,异常被存进对应的 Future,工作线程不死。只有第三处经过 try 里的 get() 被观察到,以 ExecutionException(其 cause 为原始异常)的形式浮出。
使用要点
- 只依赖工具链本身,安装步骤为零。
- 每一步打印都带着自己的标签:
handler:、serving on、future saw:。
常见问题
这个示例会校验输入吗?
不会。三处 IllegalStateException 都不检查任何输入,它们各自演示任务异常的落脚点。execute() 的抛出不在任何 try 里——异常逃出任务、到达 uncaughtExceptionHandler(打印 handler: boom)并杀死工作线程,线程池随即补上新线程;submit() 的抛出被存进 Future,线程不死;只有第三处通过 try 里的 get() 被观察到,以包装了原始异常的 ExecutionException 浮出。
运行「execute 与 submit 的异常命运不同」会打印什么?
运行文件本身,handler:、serving on、future saw: 这些前缀各对应一段演示逻辑。
核心语句
ExecutorService executor = Executors.newFixedThreadPool(1, Thread.ofPlatform()
.name("worker-", 0)
.uncaughtExceptionHandler((t, e) -> System.out.println("handler: " + e.getMessage()))
.factory());
executor.submit(() -> { throw new IllegalStateException("boom3"); }).get();
executor.execute(() -> { throw new IllegalStateException("boom"); });
代码示例
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorSurvives {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 自定义线程工厂:线程名递增 + 未捕获异常打到 stdout(避免 stderr 堆栈噪音)
ExecutorService executor = Executors.newFixedThreadPool(1, Thread.ofPlatform()
.name("worker-", 0)
.uncaughtExceptionHandler((t, e) -> System.out.println("handler: " + e.getMessage()))
.factory());
// execute():未捕获异常杀死工作线程,池创建 replacement 继续服务
executor.execute(() -> { throw new IllegalStateException("boom"); });
executor.execute(() ->
System.out.println("serving on " + Thread.currentThread().getName()));
// submit():异常被 FutureTask 捕获存进 Future,线程不死 (survives)
executor.submit(() -> { throw new IllegalStateException("boom2"); });
executor.execute(() ->
System.out.println("serving on " + Thread.currentThread().getName()));
try {
executor.submit(() -> { throw new IllegalStateException("boom3"); }).get();
} catch (ExecutionException e) {
System.out.println("future saw: " + e.getCause().getMessage());
}
executor.shutdown();
}
}