Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 713
Primk Avatar asked Apr 13 '11 09:04

Primk


2 Answers

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
like image 96
Vasil Remeniuk Avatar answered Sep 23 '22 04:09

Vasil Remeniuk


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

like image 39
DarrenWang Avatar answered Sep 21 '22 04:09

DarrenWang