Does a wait on Scala Future block thread?

巧了我就是萌 提交于 2019-12-10 03:39:34

问题


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 schedules a continuation after result if available?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/5646879/does-a-wait-on-scala-future-block-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!