Reputation: 353
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
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