我有一个重复的模式,即同时运行多个任务,要么它们全部成功,要么整个过程因其中一个任务失败而失败。虽然我可以在第一个任务异常后确定进程失败,但我必须等待所有任务结束才能报告异常。
{
List<Future<?>> futures = launchTasks();
boolean anyProcessFailed = false;
for (Future<?> future: futures)
try {
future.get();
} catch(ExecutionException ex) {
//This process failed
anyProcessFailed=true;
}
if (anyProcessFailed) throw new Exception();
}
上述代码可以运行,但是在最后抛出的异常没有提及引起它的异常(可以是一个或多个异常)。
问题是:使用Throwable.addSuppressed来实现“异常的多个原因”概念是否是一种良好的做法?还是应该实现自己的Exception类型,公开一个Throwable[] getCauses()方法?
我已经阅读过抑制异常的文档,虽然它们有一个公共API,但只能由JRE在try-with-resources语句期间设置。事实上,try-with-resources是一个普通的旧式try-finally块的语法糖。
示例1:以下代码不会等待其他任务完成,因此其他线程将被留在wild中。
{
List<Future<?>> futures = launchTasks();
for (Future<?> future: futures)
try {
future.get();
} catch(ExecutionException ex) {
//This process failed
throw new Exception(ex);
}
}
例子2:我目前在做什么
{
List<Future<?>> futures = launchTasks();
Exception ex = new Exception();
for (Future<?> future: futures)
try {
future.get();
} catch(ExecutionException e) {
//This process failed
ex.addSuppressed(e);
}
if (ex.getSuppressed().length > 0) throw ex;
}