Home > front end >  Java CompletableFuture using allOf : if one thread throws exception, how to immediately stop executi
Java CompletableFuture using allOf : if one thread throws exception, how to immediately stop executi

Time:05-07

// assume: serviceCall1 throws an exception after 1s, servserviceCall2 runs 10s without exception
CompletableFuture<String> serviceCall1Future = serviceCall1.execute();
CompletableFuture<String> serviceCall2Future = serviceCall2.execute();

CompletableFuture<Void> allOffFuture = CompletableFuture.allOf(serviceCall1Future, serviceCall2Future);

// does not work, will be called after thread 2 has finished
allOffFuture.exceptionally( ex -> { allOffFuture.cancel(true); return null; } );

try {
   // waiting for threads to finish
   allOffFuture.join();
} catch (CompletionException e) {
   // does not work, here we come after thread 2 has finished
   allOffFuture.cancel(true);
}

If one thread throws an exception, in my case it doesnt make any sense for the other thread(s) to keep on running, so I want them both (all in case of more than 2 threads) to stop . How can I achieve that ?

CodePudding user response:

I guess something like this should work:

CompletableFuture<String> serviceCall1Future = serviceCall1.execute();
CompletableFuture<String> serviceCall2Future = serviceCall2.execute();

CompletableFuture<String> foo1 = serviceCall1Future.whenComplete((result,exception) -> {if(exception != null) serviceCall2Future.cancel(true);});
CompletableFuture<String> foo2 = serviceCall2Future.whenComplete((result,exception) -> {if(exception != null) serviceCall1Future.cancel(true);});

CompletableFuture<Void> allOffFuture = CompletableFuture.allOf(foo1, foo2);

// ... rest of your code

This cancels the other future when the one completes with an exception.

CodePudding user response:

If you are using an ExecutorService with CompletableFuture, you can use Shutdowns methods like shutdown() or shutdownNow().

If you want to shut down the ExecutorService immediately, you can call the shutdownNow() method. This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt. Here is an example of calling ExecutorService shutdownNow()

See -> https://jenkov.com/tutorials/java-util-concurrent/executorservice.html#executorservice-shutdown

  • Related