开发者

Does a wait on Scala Future block thread?

When I wait for result of Scala Future, does it behave more like receive, or like react, i.e. does it block a thread, or sched开发者_StackOverflow中文版ules a continuation after result if available?


Yes, in stdlib it blocks the thread, and synchronously waits for results. If you want to apply continuation-passing style to futures, you'd have to use Akka or Scalaz that allow adding hooks on futures completion straight from the box.

Akka:

val f1 = Future { Thread.sleep(1000); "Hello" + "World" }

val f2 = f1 map { _.length }

f2 foreach println //Done asynchronously and non-blocking

Same with Scalaz:

scala> val f1 = promise {Thread.sleep(1000); "Hello" + "World"}
f1: scalaz.concurrent.Promise[java.lang.String] = scalaz.concurrent.Promise$$anon$1@1f7480

scala> val f2 = f1 map{str => str.length}
f2: scalaz.concurrent.Promise[Int] = scalaz.concurrent.Promise$$anon$1@1d40442

scala> f2.map(println)
10
res5: scalaz.concurrent.Promise[Unit] = scalaz.concurrent.Promise$$anon$1@116ad20


It should block current thread, but whether the worker thread is blocked, it depends.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜