1

I have a certain function that has exponential run time and should be executed in the background.

If a user does not wish to wait for the result, he should be able to cancel the computation with a button press. I don't want to keep anything from this computation.

Since I couldn't find a good way to cancel the computation, I embedded the algorithm into a class extending Thread and also have checks for the interrupt flag in the algorithm.

In my opinion this destroys the "beauty" of the algorithm since it is now only available with this Thread class.

I haven't done much with Futures or Actors yet. Is it possible to use them for this kind of problem? How would you approach it? Thanks in advance.

Kigyo
  • 5,668
  • 1
  • 20
  • 24
  • Why are you using threads . Are you going to run two threads at a time? – Nishant Lakhara Dec 04 '13 at 05:24
  • I'm using Threads because I don't want the GUI to be blocked. – Kigyo Dec 04 '13 at 05:54
  • Why dnt you put you algorithm into a separate class say Utils class and create a static method inside it. Call it inside the thread. – Nishant Lakhara Dec 04 '13 at 06:00
  • Do not embed algorithm into Thread class, use Runnable which you then feed into Thread. Runnable acts like a function and is separated from thread management (but it still able to terminate itself if interrupt was requested). – om-nom-nom Dec 04 '13 at 12:05
  • @om-nom-nom @flavian Assume the function is `f()` and a method `onCancel()` would end the computation. Could you provide a small example with your suggestions? – Kigyo Dec 04 '13 at 17:44

1 Answers1

0

This answer describes ways of terminating an Actor that could apply to your problem. Depending on the nature of the task, you could simply use Kill with the default supervisor strategy to stop all processing, or chunk up the processing into smaller steps triggered via a message sent to itself and use PoisonPill. More on stopping actors, including options for cleanup and restarting, here.

Community
  • 1
  • 1