Does a wait on Scala Future block thread?

风流意气都作罢 提交于 2019-12-05 04:14:20
Vasil Remeniuk

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.

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