gpt4 book ai didi

scala - Promise.completeWith 与 Promise.tryCompleteWith 有何不同?

转载 作者:行者123 更新时间:2023-12-04 02:05:11 25 4
gpt4 key购买 nike

scala.concurrent.Promise

我试图在 scaladoc 中找出 completeWithtryCompleteWith 之间的区别,但没有太多解释,也没有示例。另外,我担心以我目前的专业水平阅读源代码可能会误导我。需要您提供一些示例的建议。

最佳答案

Promise.completeWith 只是一个调用 Promise.tryCompleteWith 的包装器:

/** Completes this promise with the specified future, once that future is completed.
*
* @return This promise
*/
final def completeWith(other: Future[T]): this.type = tryCompleteWith(other)

/** Attempts to complete this promise with the specified future, once that future is completed.
*
* @return This promise
*/
final def tryCompleteWith(other: Future[T]): this.type = {
other onComplete { this tryComplete _ }
this
}

老实说,我不知道他们为什么做出这个决定,因为它看起来只是一个简单的包装器,仅此而已。

编辑

正如@Alexey Romanov 指出的那样,this GitHub issue points out the reason for this弃用:

Calling completeWith when the DefaultPromise is already completed, leads to callbacks not being properly executed.

This happened because Future.InternalCallbackExecutor extends BatchingExecutor which assumes unbatchedExecute to be async, when in this case it is sync, and if there is an exception thrown by executing the batch, it creates a new batch with the remaining items from the current batch and submits that to unbatchedExecute and then rethrows, but if you have a sync unbatchedExecute, it will fail since it is not reentrant, as witnessed by the failed require as reported in this issue.

This commit avoids problem by delegating completeWith to tryComplete, which has the effect of using onComplete + tryComplete i.s.o. complete, which means that when it fails (because of a benign race condition between completers) it won't throw an exception.

关于scala - Promise.completeWith 与 Promise.tryCompleteWith 有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44049906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com