Donatello
Donatello

Reputation: 353

ExecutorService - How to interrupt exectuion of threads which have been invoked from main thread after an exception inside one of them

I have class SomeService. Its methods can be invoked from different threads(for example from RestController). This class contains ExecutorService and some CustomClass.

public class SomeService {
   private ExecutorService service;
   private CustomClass customClass;

   public SomeService(ExecutorService service, CustomClass customClass){
       this.service = service;
       this.customClass = customClass;
   }

   public void servicePost() {
      CountDownLatch countDownLatch = new CountDownLatch(urls.size());
      for (String url : List<String> urls){
          service.submit(() -> {
              customClass.send(url);
              countDownLatch.countDown();
          });
      }
      countDownLatch.await();
   }
}

I want to execute customClass.send(url) parallel in different threads using ExecutorService but this method can throw RuntimeException.

For example, I submitted 5 tasks:
1. 2 tasks is successfully executed
2. 2 tasks are running.
3. one of them throws RuntimeException.

How can I interrupt tasks which are running?
p.s. ExecutorService can have tasks from other threads. I don't want to interrupt them.

Upvotes: 0

Views: 57

Answers (1)

Amit Bera
Amit Bera

Reputation: 7235

You can call shutdownNow() on the executor service when you catch the exception, also you need to check Thread#interrupted() inside the task before the processing. Your code should look something like below:

service.submit(() -> {
        if (!Thread.interrupted()) {
            try {
                  customClass.send(url);
                  countDownLatch.countDown();
                } catch (Exception e) {
                   service.shutdownNow();
                }
        }

    });

Upvotes: 2

Related Questions