Y.C.Jung
Y.C.Jung

Reputation: 53

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 Any

//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
    } 
  } }

  p.future
}

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 n*1000 to (n+1)*1000, it works fine(returns 0).

Is there any special effect when called sleep on 0?

Upvotes: 1

Views: 1025

Answers (2)

hminle
hminle

Reputation: 521

I think the function name is any so I think you implement any right way. But if you want the first one you just get the 1st element from the List argument fs and complete with a promise.

Upvotes: 0

engineerC
engineerC

Reputation: 2868

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 } } }

Upvotes: 1

Related Questions