0

I have to run complex, async computations and be able to abort them at any time (from outside the computation).

The current implementation uses scala.concurrent.Future to run the computations. However, there doesn't seem to be an obvious way to cancel a scala Future during execution.

I've found and tried a number of recommended solutions to this issue, such as using a Promise to implement a cancellable Future or using java.util.concurrent.Future which has a cancel() method.

All of them have the same problem: the execution only aborts when it reaches a Thread.sleep() call.

This is a problem for two reasons:

  1. The computations should finish as quickly as possible. Adding even very short sleep periods is counterproductive.
  2. I'm not the main developer of these computations and I want to avoid having to impose arbitrary constraints on the implementation of the computations.
Community
  • 1
  • 1
DrummerB
  • 39,814
  • 12
  • 105
  • 142
  • "the execution only aborts when it reaches a Thread.sleep()". That's not true. It will abort whenever suitable code is reached that checks for the interrupt status of the thread. – Kayaman Feb 21 '17 at 10:29
  • It sounds like your computations are too big if you have to worry about interrupts mid-flow. You don't say what kind of workload you have and how easily it parallelises. – Chris Mowforth Feb 21 '17 at 11:43
  • @ChrisMowforth What do you mean by "mid-flow" interrupts? I didn't go into more details about the workload, because it could be almost anything from a simple wordcount to a complex video filter or simulation. I'm providing an environment for these computations to be run in and I have to be able to kill them if needed. These computations are implemented by third parties. – DrummerB Feb 21 '17 at 12:25
  • Akka actor supervisor receives the work, spawn a child worker. Supervisor received termination notice, kills the child worker. – Diego Martinoia Mar 14 '17 at 15:01

1 Answers1

3

In the JVM you can't kill a Thread. The only safe way to stop computation is to interrupt it, which means set the flag/check the flag and stop logic. So, to stop a computation as fast as possible you need to check the interrupted flag as often as possible. Achieve it in your runnable/callable implementation and you will get the desired result.

Egor Zhuk
  • 274
  • 1
  • 7