喜欢 this question 的作者我试图理解 Scala 2.10 的 future 和 promise 中用户可见 promise 的原因。
特别是,再次访问 example from the SIP ,是不是完全有缺陷:
import scala.concurrent.{ future, promise }
val p = promise[T]
val f = p.future
val producer = future {
val r = produceSomething()
p success r
continueDoingSomethingUnrelated()
}
val consumer = future {
startDoingSomething()
f onSuccess {
case r => doSomethingWithResult()
}
}
我在想象调用
produceSomething
的情况。导致运行时异常。因为 promise 和 producer-future 完全分离,这意味着系统挂起,消费者永远不会成功或失败。因此,使用 Promise 的唯一安全方法需要类似
val producer = future {
try {
val r.produceSomething()
p success r
} catch {
case e: Throwable =>
p failure e
throw e // ouch
}
continueDoingSomethingUnrelated()
}
这显然容易出错且冗长。
我能看到的唯一一个可见 promise 类型的例子——
future {}
不够——是 M. A. D. 回答中的回调钩子(Hook)之一。但是 SIP 的例子对我来说没有意义。
最佳答案
这就是为什么你很少使用 success
和 failure
除非您已经知道某些东西是防弹的。如果你想要防弹,这就是 Try
是为了:
val producer = future {
p complete Try( produceSomething )
continueDoingSomethingUnrelated()
}
似乎没有必要再次抛出错误;您已经通过将其打包到 promise 的答案中来处理它,不是吗? (另外,请注意,如果
produceSomething
本身返回一个 future ,您可以使用 completeWith
代替。)
关于scala - promise 有缺陷吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14348382/