Search code examples
javathreadpoolexecutor

ThreadpoolExecutor , Waiting for other running thread to complete when one of the running thread throws exception


Problem statement : I am using ThreadPoolExecutor in loop to call a window process (Abby)for textual file processing.At a time there are 5 threads running which calls the window process. But in some cases one or more of the running thread throws exception. In such cases I want to allow other running threads to complete their task and threads which has thrown exception is gracefully handled after completion of running threads. How can I do that? So far I came to know that we can use ThreadExecutionCompletionService and cancel other running threads once exception occurs but my scenario is different -I want other running threads to complete

ExecutorService executorService = Executors.newCachedThreadPool();
final ExecutorCompletionService<String> completionService = 
            new ExecutorCompletionService<String>(executorService);
for (int i = 0; i < 10; ++i) {
    completionService.submit(new Task());
}

Solution

  • How about (Notice you'll have to tweak this for your own usage):

    ExecutorService executorService = Executors.newCachedThreadPool();
    
    List<CompletableFuture<Void>> futures = new ArrayList<>();
    for (int i = 0; i < 10; ++i) {
        futures.add(CompletableFuture.runAsync(
                         () -> {
                             // do work here and return
                             return work
                          },executorService)
                          .exceptionally(e -> {
                               logger.error("Error here"+e);
                               return null;
                           })
          );
    }
    CompletableFutre.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();