Search code examples
multithreadingconcurrencyarchitecturejava-8java.util.concurrent

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


I got an scenario like following.

MainClass

event.addListener(Event e){
  if (e == EXPECTED_EVENT) 
      Future<?> result = executorService.submit(myTask);
  }
}
doSomething()
doSomethingElse()
doMoreStuff()

Is there any way to interrupt the main flow in case one of the tasks fails?

I don't know where and how exactly synchronize the Exception part:

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

Any clean design to this need?


Solution

  • Consider using CompletableFuture, it allows you to compose tasks as a DAG, execute them sync or async as needed and merge results/exceptions.

    Interrupting of the futures in the graph can then be accomplished by canceling them.