Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrupt asynchronous computations in Scala?

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?

like image 597
Petr Avatar asked Oct 04 '22 18:10

Petr


1 Answers

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
like image 55
Alexey Romanov Avatar answered Oct 12 '22 12:10

Alexey Romanov