当子进程失败时,父线程中捕获的异常会中断其流程

Catched exception in parent thread interrupting its flow when child process fails

我遇到了如下情况。

主类

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();
    }

是否有针对此需求的简洁设计?

考虑使用 CompletableFuture,它允许您将任务组合为 DAG,根据需要同步或异步执行它们并合并 results/exceptions.

然后可以 canceling 中断图表中的期货。