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 Thread
s explicitly?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With