0

Below is the reference code.

Three tasks that have to be executed parallel completableFuture and cancelled all if anyone of them throws exception in Java.

Please guide me on this.

import java.util.concurrent.CompletableFuture;

public class Main
{
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Started main");
        CompletableFuture<Void> process1 = CompletableFuture.runAsync(() -> {
            System.out.println("Process 1 with exception");
            throw new RuntimeException("Exception 1");
        });
    
        CompletableFuture<Void> process2 = CompletableFuture.runAsync(() -> {
            try 
            {
                Thread.sleep(1000);
                
            } 
            catch(InterruptedException e)
            {
                    // this part is executed when an exception (in this example InterruptedException) occurs
            }
            System.out.println("Process 2 without exception");
        });
    
        CompletableFuture<Void> process3 = CompletableFuture.runAsync(() -> {
            try 
            {
                Thread.sleep(1000);
                
            } 
            catch(InterruptedException e)
            {
                    //
            }
            System.out.println("Process 3 with exception");                    
            throw new RuntimeException("Exception 3");
        });
    
        CompletableFuture<Void> allOfProcesses = CompletableFuture.allOf(process1, process2, process3);
    
        allOfProcesses.join();
        System.out.println("Ended main");
        
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Does this answer your question? [How to implement CompletableFuture.allOf() that completes exceptionally once any of the futures fail?](https://stackoverflow.com/questions/51621510/how-to-implement-completablefuture-allof-that-completes-exceptionally-once-any) – GreyBeardedGeek Dec 16 '21 at 16:12
  • 4
    Since `CompletableFuture` does not support interruption, there is no benefit in cancelling any of the futures. – Holger Dec 17 '21 at 09:39
  • @Holger Thank you for the appropriate answer to the question. – user3426127 Dec 18 '21 at 05:58

0 Answers0