rgomesf
rgomesf

Reputation: 714

JAVA - Cancel the ThreadPoolExecutor running tasks

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.

Upvotes: 6

Views: 5495

Answers (3)

John Vint
John Vint

Reputation: 40266

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.

Upvotes: 10

Affe
Affe

Reputation: 47994

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.

Upvotes: -1

Finbarr
Finbarr

Reputation: 32186

Why not create your own ExecutorService that exhibits this behaviour?

Upvotes: 0

Related Questions