scalatwitterfinagle

Twitter Future blocking


Someone can explain me why the behavior of Twitter future is not Async? Having this code

  private val future: Future[String] = Future {
    Thread.sleep(2000)
    println(s"Running this effect in ${Thread.currentThread().getName}")
    "Hello from Twitter"
  }

  println("Present")
  Await.result(future)

The output after two seconds is this one

Running this effect in main
Present

So the future is blocking and not running in another Thread


Solution

  • Twitter futures have somewhat different semantics from "standard" futures in scala.

    Future.apply is actually analogous to standard scala's Future.successful: it creates a Future that is already satisfied – so, the block you pass in is executed immediately.

    With Twitter Futures, you don't need the annoying ExecutionContext that you have to drag implicitly everywhere. Instead, you have a FuturePool to which you hand code explicitly to be asynchronously executed. E.g.:

        val pool = FuturePool.unboundedPool
        val future: Future[String] = pool {     
            Thread.sleep(2000)
            println(s"Running this effect in ${Thread.currentThread().getName}")
            "Hello from Twitter"
        }
    

    The good thing about this is that, unlike scala.concurrent, this Future is self-contained: it "knows" about the pool managing it, so, you don't need to carry it around everywhere this Future goes in case someone will need to do map or flatMap or some other transformation on it.