5

I need to run two parallel computations and interrupt the first one when the second one finishes. Currently, I've implemented it using standard Java threads:

/**
 * Runs <var>sup</var> in parallel with <var>main</var>.
 * Terminate (interrupt) it when <var>main</var> finishes.
 */
def support[R](sup: => Unit, main: => R): R = {
  val supThread = new Thread {
    override def run = { sup };
  }

  supThread.start();
  try {
    main;
  } finally {
    supThread.interrupt();
  }
}

Can the same behavior be achieved using Scala's concurrent library, without using Threads explicitly?

Petr
  • 62,528
  • 13
  • 153
  • 317
  • http://stackoverflow.com/questions/14449862/kill-or-timeout-a-future-in-scala-2-10/14450095#14450095 – sourcedelica Mar 10 '13 at 15:01
  • Your implementation with Java's API is not reliable - interrupt doesn't always work as expected and should probably never be used. It's better to code explicitly for early termination - e.g. as in the answer linked in the comment above. Sharing an AtomicBoolean is one of the (many) possible solutions. – Rick-777 Mar 11 '13 at 13:27

1 Answers1

4

Not with Scala standard futures (AFAIK), but Twitter's Util library does support it:

val future = Future { sup }
future.cancel() // in 5.x
future.raise(new FutureCancelledException) // in 6.x
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487