Since you don't seem to be using the CompletableFuture specific methods, you could use an ExecutorService
directly:
for (int i = 0; i < 100; i++) {
executor.submit(() -> {
try {
someTask();
} catch (InterruptedException e) {
//interrupted, just exit
Thread.currentThread().interrupt();
} catch (Exception e) {
//some other exception: cancel everything
executorService.shutdownNow();
}
});
}
shutdownNow
will interrupt all the already submitted tasks and the executor will refuse new task submission with a RejectedExecutionException
.
The main drawback with this approach is that the ExecutorService cannot be reused, although you can of course create a new one. If that's a problem you will need another way.
Note that for this to work efficiently someTask()
needs to regularly check the interrupted status of the thread and exit on interruption, or use interruptible methods. For example if someTask
is a loop running some calculations and you never check the Thread interrupted status, the loop will run entirely and will not be stopped.