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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With