Reputation: 32253
I'd like to cancel all the tasks waiting in a ThreadPoolExecutor.
For example if the tasks A and B are running and C,D,E waiting (because the thread pool size is 2) I want to cancel C,D,E leaving A and B end normally.
How can I do this in a easy way other than maintaining the list of the Runnables and calling threadpool.remove(runnable) for each one of them?
Thanks
Upvotes: 1
Views: 86
Reputation: 50036
You could call .cancel() on your tasks that you want to remove - ie. iterate some list with tasks and check using instanceof
if they are of C,D,E type. As a list you could use threadPoolExector.getQueue()
as KamiSempai suggested.
I am actually using ScheduledExecutorService
and I have method:
cancelTasksOfType(Class<? extends TaskBase) taskClassToCancel)
inside it I'am cancelling each task that passes test with instanceof
on taskClassToCancel
Upvotes: 1
Reputation: 188
All tasks that not running placed in special queue. You can get this queue via getQueue().
Your code should looks like this:
threadPoolExector.getQueue().clear();
Upvotes: 3