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.