Scala Future `.onComplete` 函数在调用后被丢弃?
Scala Future `.onComplete` function discarded after call?
函数体是否传递给 Future.onComplete()
,它们的闭包是否在被调用后被丢弃并因此被垃圾收集?
我问是因为我正在编写 Future
实例的无限序列。每个 Future
都有一个 .onComplete { case Failure(t)...}
,它指的是来自先前 Future
的先前已知良好值。我想避免的是所有 Future
结果的总历史记录由于闭包体中的引用而保存在 JVM 的内存中。
也许 Scala 比这更聪明,但浏览与执行上下文和 futures 相关的代码并没有太多收获。
谢谢。
通常实现 Future
而您想查看的 class 是 DefaultPromise
。
它包含随着 Future 完成而更新的可变状态。
- 如果您调用
onComplete
并且它已经完成,那么它会立即安排您的回调和结果。回调没有被记录在任何地方。
- 如果您在结果尚未可用时调用
onComplete
,回调将添加到 "listeners" 的列表中。
- 当结果可用时(有人在 promise 上调用
complete
),然后所有侦听器都被安排到 运行 使用该结果,并且侦听器列表被删除(内部状态更改至 "completed with this result")
这意味着您的回调链只会在 "upstream future" 不完整之前建立。在那之后,一切都得到解决 garbage-collected。
上面的 "list of listeners" 有点简化。需要特别注意的是,这些侦听器不会最终引用 each-other,特别是要打破在递归构造 futures 时阻止垃圾收集工作的引用循环。显然这在早期版本中确实是一个问题。
The problem of leaks is solved by automatically breaking these chains of promises, so that promises don't refer to each other in a long chain. This
allows each promise to be individually collected. The idea is to "flatten"
the chain of promises, so that instead of each promise pointing to its
neighbour, they instead point directly the promise at the root of the
chain. This means that only the root promise is referenced, and all the
other promises are available for garbage collection as soon as they're no
longer referenced by user code.
函数体是否传递给 Future.onComplete()
,它们的闭包是否在被调用后被丢弃并因此被垃圾收集?
我问是因为我正在编写 Future
实例的无限序列。每个 Future
都有一个 .onComplete { case Failure(t)...}
,它指的是来自先前 Future
的先前已知良好值。我想避免的是所有 Future
结果的总历史记录由于闭包体中的引用而保存在 JVM 的内存中。
也许 Scala 比这更聪明,但浏览与执行上下文和 futures 相关的代码并没有太多收获。
谢谢。
通常实现 Future
而您想查看的 class 是 DefaultPromise
。
它包含随着 Future 完成而更新的可变状态。
- 如果您调用
onComplete
并且它已经完成,那么它会立即安排您的回调和结果。回调没有被记录在任何地方。 - 如果您在结果尚未可用时调用
onComplete
,回调将添加到 "listeners" 的列表中。 - 当结果可用时(有人在 promise 上调用
complete
),然后所有侦听器都被安排到 运行 使用该结果,并且侦听器列表被删除(内部状态更改至 "completed with this result")
这意味着您的回调链只会在 "upstream future" 不完整之前建立。在那之后,一切都得到解决 garbage-collected。
上面的
"list of listeners" 有点简化。需要特别注意的是,这些侦听器不会最终引用 each-other,特别是要打破在递归构造 futures 时阻止垃圾收集工作的引用循环。显然这在早期版本中确实是一个问题。
The problem of leaks is solved by automatically breaking these chains of promises, so that promises don't refer to each other in a long chain. This allows each promise to be individually collected. The idea is to "flatten" the chain of promises, so that instead of each promise pointing to its neighbour, they instead point directly the promise at the root of the chain. This means that only the root promise is referenced, and all the other promises are available for garbage collection as soon as they're no longer referenced by user code.