Terminate all threads when exception occurs for one in an asynchronous method

Viewed 465

Is it possible to immediately interrupt all other threads execution, if an exception is encountered in any one of the thread in an asynchronous method? The method returns a completableFuture Object.

    @Async("asyncTaskExecutor")
public CompletableFuture<String> updateOp(String department, List<Student> student, Boolean flag)
{
....
....
return departmentId;
}

This async method is called by another service class method:

    public List<String> updateDepartments
{
....
....
try {
List<CompletableFuture<String>> futures = new ArrayList<>();
for (String department: departmentList) {
            CompletableFuture<String> departmentId= updateAsyncService.updateOp(department,
                    studentList, statusFlag);
            futures.add(departmentId);
        }
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
        for (CompletableFuture<String> future : futures) {
            departmentIdList.add(future.get());
        }
} catch (Exception e) {
        logger.error(e);
        } 
return departmentIdList;
}

The above method runs for various departments asynchronously. Now if the update operation fails for any department (exception occurs in any thread while running updateOp), I want all threads to stop their execution.

Also, in such a case how would I retrieve for which departments did the updateOp run successfully, to basically get a list of those department Ids. Thanks for any help in advance.

1 Answers

Not sure if join() will really fulfill your purpose here. Try handling it like below code snippet. Good luck!

            boolean flag = false;
            for (Future<Void> future : futureSet ) {
                try {
                    future.get();
                } catch (InterruptedException e) {
                    System.out.println("Interrupted");
                } catch (ExecutionException e) {
                    System.out.println("Exception thrown from the thread");
                    flag = true;
                    break;
                }
            }

            if(flag) {
                for (Future<Void> future : futureSet) {
                    future.cancel(true);
                }
            }
Related