stateless-future 异步编程 Future

我要开发同款
匿名用户2014年04月18日
48阅读
开发技术Scala
所属分类常用工具包、程序开发
授权协议Apache

作品详情

stateless-future用于异步编程的纯函数风格Future

示例代码:

import scala.concurrent.duration._import scala.util.control.Exception.Catcherimport com.qifun.statelessFuture.Futureval executor = java.util.concurrent.Executors.newSingleThreadScheduledExecutor// Manually implements a stateless future, which is the asynchronous version of `Thread.sleep()`def asyncSleep(duration: Duration) = new Future[Unit] {  import scala.util.control.TailCalls._  def onComplete(handler: Unit => TailRec[Unit])(implicit catcher: Catcher[TailRec[Unit]]) = {    executor.schedule(new Runnable {      def run() {        handler().result      }    }, duration.length, duration.unit)    done()  }}// Without the keyword `new`, you have the magic version of `Future` constructor,// which enables the magic postfix `await`.val sleep10seconds = Future {  var i = 0  while (i < 10) {    println(s"I have sleeped $i times.")    // The magic postfix `await` invokes the asynchronous method `asyncSleep`.    // It looks like normal `Thread.sleep()`, but does not block any thread.    asyncSleep(1.seconds).await    i += 1  }  i}// When `sleep10seconds` is running, it could report failures to this catcherimplicit def catcher: Catcher[Unit] = {  case e: Exception => {    println("An exception occured when I was sleeping: " + e.getMessage)  }}// A stateless future instance is lazy, only evaluating when you query it.println("Before the evaluation of the stateless future `sleep10seconds`.")for (total <- sleep10seconds) {  println("After the evaluation of the stateless future `sleep10seconds`.")  println(s"I sleeped $total times in total.")  executor.shutdown()}

输出结果:

Before evaluation of the stateless future `sleep10seconds`.I have sleeped 0 times.I have sleeped 1 times.I have sleeped 2 times.I have sleeped 3 times.I have sleeped 4 times.I have sleeped 5 times.I have sleeped 6 times.I have sleeped 7 times.I have sleeped 8 times.I have sleeped 9 times.After evaluation of the stateless future `sleep10seconds`.I sleeped 10 times in total.
查看全文
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论