i have this rather simple question about the ThreadPoolExecutor. I have the following situation: I have to consume objects from a queue, create the appropiate worker tasks f
Tell your thread pool to shutdown, getQueue, for-each the result into individual Runnables, remove each Runnable using the remove method. Depending on the type of queue, you might be able to halt the removes early based on return values.
Basically, this is grabbing the queue and clearing it, only clearing via the methods that work. Instead of manually remembering all the submissions, you use the fact the thread pool already has to remember all the submissions. However, you will probably need to make a defensive copy of the queue, as I think it's a live view, and therefore removing would probably cause a concurrent modification exception if you were iterating/for-eaching over the live view.
Doesn't awaitTermination(long timeout, TimeUnit unit)
work after shutdown?
executor.shutdown(); executor.awaitTermination(60, TimeUnit.SECONDS)
This is an old question, but in case this helps somebody else: you could set a volatile boolean when you call shutdown(), and have each submitted task terminate if that boolean is set before really starting. This will allow tasks which have genuinely started to complete, but will prevent queued tasks from starting their actual activity.
Bombe's answer is exactly what you want. shutdownNow()
stops everything using the nuke and pave approach. This is the best thing you can do, short of subclassing the implementation of ThreadPoolExecutor
that you're using.