views:

131

answers:

4

What I need is a method similar to shutdownNow, but, be able to submit new tasks after that. My ThreadPoolExecutor will be accepting a random number of tasks during my program execution.

A: 

Why not create your own ExecutorService that exhibits this behaviour?

Finbarr
A: 

Have a look at the getQueue() method. I'm pretty sure that clearing it would work (not tested however).

someguy
GetQueue() can only clean the tasks in the queue. Can't do anything with the already running tasks..
rgomesf
A: 

Is it not enough to just do getQueue() and clear it? If you really need to attempt to stop running tasks, you would need to subclass the ThreadPoolExecutor and essentially re-implement shutdownNow() but only copy the bit that sends an interrupt to each thread. Mind you this still isn't any guarantee that you will actually cause them to immediately cease and do no further calculation. You'll need a totally different approach if you need to do that.

Affe
I already tried to re-implement shutdownNow() but some variables are private, and without them I can't do what I want...
rgomesf
+2  A: 

You can grab the Future of each submission, store that Future in a collection, then when you want to cancel the tasks, invoke future.cancel() of all queued tasks.

With this solution the Exectuor is still running and any running tasks are cancelled or will not run if they are queued.

John V.
Thanks, my only question regarding your solutions was about the size of the collection because my ThreadPoolExecutor will be receiving unlimited tasks. But with a Map<Runnable,Future> and overwriting submit and afterExecute I can maintain my collection with the running tasks only.
rgomesf