stateless-future异步编程 Future

联合创作 · 2023-09-28 17:42

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

示例代码:

import scala.concurrent.duration._
import scala.util.control.Exception.Catcher
import com.qifun.statelessFuture.Future

val 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 catcher
implicit 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.
浏览 5
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报