Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With a Java ExecutorService, how do I complete actively executing tasks but halt the processing of waiting tasks?

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:

  1. I can call ExecutorService.shutdown() and then ExecutorService.awaitTermination(...).
  2. 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.

like image 230
Jeff Goldberg Avatar asked Nov 16 '11 20:11

Jeff Goldberg


People also ask

Which method can cancel the Future task triggered by submit () of ExecutorService?

You can cancel the task submitted to ExecutorService by simply calling the cancel method on the future submitted when the task is submitted.

Does ExecutorService shutdown automatically?

In general, the ExecutorService will not be automatically destroyed when there is no task to process. It will stay alive and wait for new tasks to come. It simply means that JVM will not terminate if we are expecting it to.

How do I stop a thread in ExecutorService?

To properly shut down an ExecutorService, we have the shutdown() and shutdownNow() APIs. The shutdown() method doesn't cause immediate destruction of the ExecutorService. It will make the ExecutorService stop accepting new tasks and shut down after all running threads finish their current work: executorService.


2 Answers

I ran into this issue recently. There may be a more elegant approach, but my solution is to first call shutdown(), then pull out the BlockingQueue being used by the ThreadPoolExecutor and call clear() on it (or else drain it to another Collection for storage). Finally, calling awaitTermination() allows the thread pool to finish what's currently on its plate.

For example:

public static void shutdownPool(boolean awaitTermination) throws InterruptedException {

    //call shutdown to prevent new tasks from being submitted
    executor.shutdown();

    //get a reference to the Queue
    final BlockingQueue<Runnable> blockingQueue = executor.getQueue();

    //clear the Queue
    blockingQueue.clear();
    //or else copy its contents here with a while loop and remove()

    //wait for active tasks to be completed
    if (awaitTermination) {
        executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS);
    }
}

This method would be implemented in the directing class wrapping the ThreadPoolExecutor with the reference executor.

It's important to note the following from the ThreadPoolExecutor.getQueue() javadoc:

Access to the task queue is intended primarily for debugging and monitoring. This queue may be in active use. Retrieving the task queue does not prevent queued tasks from executing.

This highlights the fact that additional tasks may be polled from the BlockingQueue while you drain it. However, all BlockingQueue implementations are thread-safe according to that interface's documentation, so this shouldn't cause problems.

like image 60
Paul Bellora Avatar answered Sep 19 '22 15:09

Paul Bellora


The shutdownNow() is exactly what you need. You've missed the 1st word Attempts and the entire 2nd paragraph of its javadoc:

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

So, only tasks which are checking Thread#isInterrupted() on a regular basis (e.g. in a while (!Thread.currentThread().isInterrupted()) loop or something), will be terminated. But if you aren't checking on that in your task, it will still keep running.

like image 32
BalusC Avatar answered Sep 18 '22 15:09

BalusC