I am using an ExecutorService (a ThreadPoolExecutor) to run (and queue) a lot of tasks. I am attempting to write some shut down code that is as graceful as possible.
ExecutorService has two ways of shutting down:
- I can call
ExecutorService.shutdown()
and thenExecutorService.awaitTermination(...)
. - I can call
ExecutorService.shutdownNow()
.
According to the JavaDoc, the shutdown
command:
Initiates an orderly shutdown in which previously submitted
tasks are executed, but no new tasks will be accepted.
And the shutdownNow
command:
Attempts to stop all actively executing tasks, halts the
processing of waiting tasks, and returns a list of the tasks that were
awaiting execution.
I want something in between these two options.
I want to call a command that:
a. Completes the currently active task or tasks (like shutdown
).
b. Halts the processing of waiting tasks (like shutdownNow
).
For example: suppose I have a ThreadPoolExecutor with 3 threads. It currently has 50 tasks in the queue with the first 3 actively running. I want to allow those 3 active tasks to complete but I do not want the remaining 47 tasks to start.
I believe I can shutdown the ExecutorService this way by keeping a list of Future
objects around and then calling cancel
on all of them. But since tasks are being submitted to this ExecutorService from multiple threads, there would not be a clean way to do this.
I'm really hoping I'm missing something obvious or that there's a way to do it cleanly.
Thanks for any help.
Best Answer
I ran into this issue recently. There may be a more elegant approach, but my solution is to first call
shutdown()
, then pull out theBlockingQueue
being used by theThreadPoolExecutor
and callclear()
on it (or else drain it to anotherCollection
for storage). Finally, callingawaitTermination()
allows the thread pool to finish what's currently on its plate.For example:
This method would be implemented in the directing class wrapping the
ThreadPoolExecutor
with the referenceexecutor
.It's important to note the following from the
ThreadPoolExecutor.getQueue()
javadoc:This highlights the fact that additional tasks may be polled from the
BlockingQueue
while you drain it. However, allBlockingQueue
implementations are thread-safe according to that interface's documentation, so this shouldn't cause problems.