1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
import scala.concurrent._
import java.util.concurrent.atomic.AtomicInteger
object Test {
def main(args: Array[String]) {
test()
}
def test() = {
def await(f: Future[Any]) =
Await.result(f, duration.Duration.Inf)
val ec = new TestExecutionContext(ExecutionContext.Implicits.global)
{
val p = Promise[Int]()
val fp = p.future
println("mapping")
val mapped = fp.map(x => x)(ec)
p.success(0)
await(mapped)
}
{
println("flatmapping")
val p = Promise[Int]()
val fp = p.future
val flatMapped = fp.flatMap({ (x: Int) =>
Future.successful(2 * x)
})(ec)
p.success(0)
await(flatMapped)
}
{
println("recovering")
val recovered = Future.failed(new Throwable()).recoverWith {
case _ => Future.successful(2)
}(ec)
await(recovered)
}
}
class TestExecutionContext(delegate: ExecutionContext) extends ExecutionContext {
def execute(runnable: Runnable): Unit = ???
def reportFailure(t: Throwable): Unit = ???
override def prepare(): ExecutionContext = {
val preparedDelegate = delegate.prepare()
return new ExecutionContext {
def execute(runnable: Runnable): Unit = {
println("execute()")
preparedDelegate.execute(runnable)
}
def reportFailure(t: Throwable): Unit = ???
}
}
}
}
|