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