I currently have an ExecutorService where I want the following:
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?
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With