Lucas Werkmeister
Lucas Werkmeister

Reputation: 2752

Is there a way to cancel and reuse an ExecutorService?

I am writing a Java Fractal Explorer, and the fractal calculation is done multi-threaded. Previously, I just created a bunch of threads (as many as the system has processor cores) and held them in an array, but this results in a several problems and is not very elegant, and now I want to switch to Executors.

The functionality I need is:

My problem is that the Java ExecutorService (I use an Executors.newFixedThreadPool()) throws exceptions when I submit new tasks after a call to shutdownNow() (cancelling). I could of course just create a new ExecutorService, but then all the threads would have to be created again, which is, as far as I understand, quite expensive (which is the whole point of using thread pools).

So basically what I need is a ExecutorService implementation using a thread pool that can be cancelled without shutting it down, so it can be reused.

Is there already such a thing or do I have to write it myself? (Can't be too hard, right? ;) )

My current code can be found at https://github.com/lucaswerkmeister/JFractalizer.

Thanks in advance,

Lucas

PS: When using executors, I would split the image in more parts than there are threads, so if one part finishes much faster, the thread is not idle, but can instead continue on another part of the image. It would be cool if nevertheless all the parts would be calculated in parallel and not some starting later than others, but that's just a bonus.

Upvotes: 2

Views: 1716

Answers (2)

reprogrammer
reprogrammer

Reputation: 14728

You should use ExecutorService.html#shutdownNow() when you're done with the ExecutorService and you don't intend to submit new tasks to it.

If you want to keep using the same ExecutorService, you should cancel the individual tasks.

Method ExecutorService.html#submit returns a Future that can be used to cancel execution and/or wait for completion.

Upvotes: 2

rai.skumar
rai.skumar

Reputation: 10675

Your task should be able to handle interrupts. So you can cancel task by interrupting them.

  boolean flag = Thread.interrupted();
  if(flag == true )
      throw new InterruptedException();

Upvotes: 1

Related Questions