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

StackOverflow https://stackoverflow.com/questions/22690415

  •  22-06-2023
  •  | 
  •  

Domanda

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?

È stato utile?

Soluzione

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;
    }
}

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top