com.twitter.util.Await doesn't raise a com.twitter.util.TimeoutException

944 views Asked by At

I expect that this code will raise a TimeoutException, but it doesn't. What do I do wrong?

import com.twitter.conversions.time._
import com.twitter.util.{Await, Future}


object Tmp {

  def main(args: Array[String]): Unit = {
    Await.result(
      Future{
        Thread.sleep(10000000)
      },
        1 second
    )
  }
}
1

There are 1 answers

0
Hinse ter Schuur On BEST ANSWER

The scaladoc of the Future.apply method has a note which states that:

a is executed in the calling thread and as such some care must be taken with blocking code.

So in general you should not perform blocking operations with Futures.

If you want to do blocking calls you should use com.twitter.util.FuturePool. Some more background on performing blocking calls can be found in the Blocking or synchronous work section of the Twitter Util documentation.

So your code could look like this:

import com.twitter.conversions.time._
import com.twitter.util.{Await, FuturePool}

object Tmp {
  def main(args: Array[String]): Unit = {
    Await.result(
      FuturePool.unboundedPool {
        Thread.sleep(5000)
      },
      1 second
    )
  }
}

In this example I used the unboundedPool as a quick example. But please check the FuturePool documentation for finding the appropriate FuturePool for your usecase.