1

how to remove all the running and queued tasks in ExecutorService and add new tasks into it?

There is a ExecutorService to deal with the new tasks coming in each round.
If tasks are not done in this round, remove these old tasks and add news coming tasks in next round. ExecutorService will be reused in next round, so ExecutorService cannot be shutdown.
Anybody knows how to do it?

ejxqy
  • 11
  • 2

1 Answers1

2

how to remove all the running and queued tasks in ExecutorService and add new tasks into it?

Adding is easy - just call submit. Removing on the other hand is trickier - you can call shutdownNow. Javadoc:

Attempts to stop all actively executing tasks, halts theprocessing of waiting tasks, and returns a list of the tasks that were awaiting execution.

However shutdownNow() will actually shut down the executor, so it'll refuse to accept new tasks. Also, note the word attempts in the Javadoc. Once a task started executing, there's no guarantee it can be easily stopped. Tasks can ignore interrupt and keep running.

If you want more granular control, don't use an ExecutorService. Instead, try a ThreadPoolExecutor, which implements ExecutorService. In a ThreadPoolExecutor you have direct access to the queue of Runnables.

Malt
  • 28,965
  • 9
  • 65
  • 105