0

I have a requirement where I execute number of threads on a daily basis. Each thread does some task. The problem I am trying to solve is if to terminate the executor service gracefully using a stopfile that is passed as a parameter.

I am using the approach of checking the stopfile in the thread's run method, but it will do an empty run for all the remaining tasks. Instead I looking for a way to stop the tasks in the executorservice itself. Is there a way to do that.

I was looking at this post: Removing all queued tasks of an ThreadPoolExecutor

Can someone expand more on this?

Community
  • 1
  • 1
nithatech
  • 1
  • 1

1 Answers1

1

I am using the approach of checking the stopfile in the thread's run method, but it will do an empty run for all the remaining tasks. Instead I looking for a way to stop the tasks in the executorservice itself. Is there a way to do that.

I think the right way to stop the ExecutorService is to use the executorservice.shutdownNow(); method on it. This will cancel any jobs that have not been run and will interrupt all of the running threads.

To test for the interrupt, your tasks should do something like:

while (!Thread.currentThread().isInterrupted()) {
    ...
}

Anyplace you catch InterruptedException, you need to make sure you re-enable the interrupt flag:

try {
    // something that throws InterruptedException
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    // maybe we should quit the thread here
}

If you are using third party libraries that may eat the InterruptedException then you should maye have to use the executorservice.shutdown() that will cancel the jobs but not interrupt the threads. Then you should share some sort of volatile boolean shutdown flag (or AtomicBoolean) and do something in your run methods:

while (!Thread.currentThread().isInterrupted() && !shutdown) {
    ...
}

Btw, you mention the "thread's run method". Just to be sure, you should be implementing Runnable and submitting those to the ExecutorService. You should not be submitting Thread instances.

Gray
  • 115,027
  • 24
  • 293
  • 354