How to interrupt asynchronous calculations in Scala?

I need to start two parallel computations and abort the first when the second ends. I have currently 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();
  }
}

Is it possible to achieve the same result using the Scala parallel library without using it explicitly Thread?

+5
source share
1 answer

Not with Scala Standard Futures (AFAIK), but the Twitter Util library supports it:

val future = Future { sup }
future.cancel() // in 5.x
future.raise(new FutureCancelledException) // in 6.x
+4
source

All Articles