Scala Future 和 Thread.sleep 的奇怪行为
Weird Behavior of Scala Future and Thread.sleep
我目前正在编写代码来扩展 Future 伴随对象。我要实现的一个功能是 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
}
我尝试用
测试我的代码
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)
}
但是返回值是1,不是0。当我把睡眠时间从n*1000
切换到(n+1)*1000
时,它工作正常(returns 0)。
调用sleep on 0有什么特殊效果吗?
Thread.sleep
是您的 Future
中的阻塞操作,但您并未向 ExecutionContext
发出您正在这样做的信号,因此行为会因您使用的 ExecutionContext 而异以及您的机器有多少个处理器。如果您添加 blocking
:
,您的代码将按预期使用 ExecutionContext.global
nums map { n => Future { blocking { Thread.sleep(n*1000); n } } }
我认为函数名称是 any
,所以我认为您实现 any
的方式是正确的。
但是,如果您想要第一个,您只需从 List 参数 fs
中获取第一个元素并完成承诺。
我目前正在编写代码来扩展 Future 伴随对象。我要实现的一个功能是 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
}
我尝试用
测试我的代码 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)
}
但是返回值是1,不是0。当我把睡眠时间从n*1000
切换到(n+1)*1000
时,它工作正常(returns 0)。
调用sleep on 0有什么特殊效果吗?
Thread.sleep
是您的 Future
中的阻塞操作,但您并未向 ExecutionContext
发出您正在这样做的信号,因此行为会因您使用的 ExecutionContext 而异以及您的机器有多少个处理器。如果您添加 blocking
:
ExecutionContext.global
nums map { n => Future { blocking { Thread.sleep(n*1000); n } } }
我认为函数名称是 any
,所以我认为您实现 any
的方式是正确的。
但是,如果您想要第一个,您只需从 List 参数 fs
中获取第一个元素并完成承诺。