Created
May 22, 2014 21:03
-
-
Save dant3/678a4329f96cde3f6836 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.actforex.nst | |
import java.util.concurrent.{CancellationException, Executors, FutureTask, Callable} | |
import scala.concurrent.{ExecutionContext, Future} | |
import ExecutionContext.Implicits.global | |
trait CancelForFuture { | |
def cancel(mayInterruptIfRunning:Boolean):Boolean | |
} | |
case class FutureWithCancel[T](future:Future[T], futureTask: FutureTask[_]) extends CancelForFuture { | |
def cancel(mayInterruptIfRunning: Boolean): Boolean = futureTask.cancel(mayInterruptIfRunning) | |
def map[S](f: T => S)(implicit executor: ExecutionContext) = new FutureWithCancel(future.map(f), futureTask) | |
def flatMap[S](f: T => FutureWithCancel[S])(implicit executor: ExecutionContext) = new FutureWithCancel(future.flatMap((t:T) => f(t).future), futureTask) | |
def filter(pred: T => Boolean)(implicit executor: ExecutionContext): FutureWithCancel[T] = new FutureWithCancel(future.filter(pred), futureTask) | |
def withFilter(p: T => Boolean)(implicit executor: ExecutionContext): FutureWithCancel[T] = new FutureWithCancel(future.withFilter(p), futureTask) | |
def foreach[U](f: T => U)(implicit executor: ExecutionContext) = future.foreach(f) | |
} | |
object FutureWithCancel { | |
def apply[T](body: =>T)(implicit executor: ExecutionContext):FutureWithCancel[T] = { | |
val cancelTask = new FutureTask[T](new Callable[T]() { | |
def call(): T = { | |
body | |
}}) | |
new FutureWithCancel[T](Future[T] { cancelTask.run(); cancelTask.get() }, cancelTask) | |
} | |
} | |
object Sample { | |
def main(args: Array[String]) { | |
val f1 = FutureWithCancel[String] { | |
println("Started") | |
this.synchronized{ | |
try { | |
wait() // Blocking | |
} catch { | |
case e: InterruptedException => | |
} | |
} | |
println("Finished canceled task") | |
"Hello" + "World" | |
} | |
val f2 = f1 map { x ⇒ | |
x.length | |
} | |
f2 foreach println | |
f2.future.onFailure { | |
case e: CancellationException ⇒ println("future was canceled") | |
} | |
Thread.sleep(100) | |
println("try cancel") | |
f2.cancel(true) | |
Thread.sleep(100) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment