Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Middle ground between ExecutorService.shutDown() and ExecutorService.shutDownNow()

I currently have an ExecutorService where I want the following:

  • No new tasks should be accepted.
  • Current tasks should still keep on executing.
  • All currently queued up tasks should be returned.

The issue I am facing is that the shutdown() will not return any non-executing submitted tasks (in fact it will wait until al tasks have been completed), while the shutdownNow() will abruptly try to kill all already existing tasks.

How should I work around this?

like image 700
skiwi Avatar asked Feb 03 '26 07:02

skiwi


2 Answers

You should be able to accomplish this by creating your own class that extends ThreadPoolExecutor and providing your own shutdown method.

Below is an example for how this could be done, you might want to adjust it to your needs (providing more constructor methods for example)

public class MyExecutor extends ThreadPoolExecutor {

    private final BlockingQueue<Runnable>   queue;

    public MyExecutor(int corePoolSize,
            int maximumPoolSize,
            long keepAliveTime,
            TimeUnit unit,
            BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        this.queue = workQueue;
    }

    public List<Runnable> shutdownSpecial() {
        ArrayList<Runnable> queued = new ArrayList<>();
        queue.drainTo(queued);
        this.shutdown();
        return queued;
    }
}
like image 197
Simon Forsberg Avatar answered Feb 04 '26 21:02

Simon Forsberg


You can do something like follows:

As you know, ExecutorService ThreadPool implementations uses a BlockingQueue (bounded or unbounded queue) as a holder to keep your jobs (runnable).

So, considering your requirement you just have to do something like this:

yourWorkqueue.clear();

And after that, you can call

executor.shutdown();

AFAIK, the currently executing jobs would not be there in the Queue. So, the thread in the pool will keep on working on the jobs in hand while you will clear the Job Queue.

like image 26
sakura Avatar answered Feb 04 '26 20:02

sakura



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!