我有一个像下面这样的场景。
MainClass
event.addListener(Event e){
if (e == EXPECTED_EVENT)
Future<?> result = executorService.submit(myTask);
}
}
doSomething()
doSomethingElse()
doMoreStuff()
如果其中一个任务失败,有没有办法打断主流?
我不知道在哪里以及如何完全同步异常部分:
try {
Object result = ((Future<?>) expectedFutureTask).get();
}
catch (InterruptedException e ) { /* Task was interupted/stopped */}
catch (CancellationException e) { /* Task was cancelled */}
catch (ExecutionException e) { //Task threw an Exception
throw e.getCause();
}
这种需要的任何干净设计?
答案 0 :(得分:1)
考虑使用CompletableFuture,它允许您将任务组合为DAG,根据需要执行同步或异步并合并结果/异常。
然后可以通过canceling来中断图表中的期货。