【发布时间】:2018-11-14 19:14:34
【问题描述】:
我正在创建一些任务,如下所示(这仅用于演示通常的网络调用):
public class RandomTask implements Function<String, String> {
private int number;
private int waitTime;
private boolean throwError;
public RandomTask(int number, int waitTime, boolean throwError) {
this.number = number;
this.waitTime = waitTime;
this.throwError = throwError;
}
@Override
public String apply(String s) {
System.out.println("Job " + number + " started");
try {
Thread.sleep(waitTime);
if (throwError) {
throw new InterruptedException("Something happened");
}
} catch (InterruptedException e) {
System.out.println("Error " + e.getLocalizedMessage());
}
return "RandomTask " + number + " finished";
}
}
然后我有一个 Chain 类,我在其中将每个作业的一些任务链接在一起。
static CompletableFuture<String> start(ExecutorService executorService) {
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Foo", executorService)
.thenApplyAsync(new RandomTask(3, 100, false), executorService)
.thenApplyAsync(new RandomTask(4, 100, false), executorService);
return future2;
}
然后我按如下方式启动 2 个链:
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(Chain1.start(fixedThreadPool), Chain2.start(fixedThreadPool));
try {
combinedFuture.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
这样两条链同时开始。
现在我想在一个任务中抛出一个异常,并在我调用 combineFuture.get() 的地方捕获它,以便我知道哪个任务在我的链中失败了。
问题是我无法调整函数,因为 CompletableFutures 抱怨这一点。我试过了:
@FunctionalInterface
public interface CheckedFunction<T, R> {
R apply(T t) throws InterruptedException;
}
但这不起作用。这是不可能的吗?或者我怎样才能实现我的目标?
【问题讨论】: