質問

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:

  • The user can, at any time, select a new area of the fractal image to zoom into, so it should be possible to cancel the calculation at any time, and immediately reinsert new tasks
  • For better performance, threads should be reused (and survive a cancellation)

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.

役に立ちましたか?

解決

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.

他のヒント

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();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top