Y.C.Jung Y.C.Jung - 1 year ago 141
Scala Question

Weird Behavior of Scala Future and Thread.sleep

I'm currently writing codes to extend the Future companion object. One function I want to implement is


//returns the future that computes the first value computed from the list. If the first one fails, fail.
def any[T](fs: List[Future[T]]): Future[T] = {
val p = Promise[T]()

fs foreach { f => {
f onComplete {
case Success(v) => p trySuccess v
case Failure(e) => p tryFailure e
} }


I tried to test my code with

test("A list of Futures return only the first computed value") {
val nums = (0 until 10).toList
val futures =
nums map { n => Future { Thread.sleep(n*1000); n } }

val v = Await.result(Future.any(futures), Duration.Inf)

assert(v === 0)

But the returned value is 1, not 0. When I switched sleeping time to
, it works fine(returns 0).

Is there any special effect when called sleep on 0?

Answer Source

Thread.sleep is a blocking operation in your Future but you are not signaling to the ExecutionContext that you are doing so, so the behavior will vary depending on what ExecutionContext you use and how many processors your machine has. Your code works as expected with ExecutionContext.global if you add blocking:

nums map { n => Future { blocking { Thread.sleep(n*1000); n } } }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download