Scala Future `.onComplete` 函数在调用后被丢弃?

标签 scala concurrent.futures

函数体是否传递给 Future.onComplete(),它们的闭包是否在调用后被丢弃并因此被垃圾收集?

我问是因为我正在编写无限序列的 Future 实例。每个 Future 都有一个 .onComplete { case Failure(t)...},它引用来自先前 Future 的先前已知良好值.我想避免的是所有 Future 结果的全部历史记录都保存在 JVM 的内存中,因为闭包体中有引用。

也许 Scala 比这更聪明,但浏览与执行上下文和 futures 相关的代码并没有太多收获。

谢谢。

最佳答案

通常实现 Future 并且您想查看的类是 DefaultPromise

它包含随着 Future 完成而更新的可变状态。

  • 如果您调用 onComplete 并且它已经完成,那么它会立即安排您的回调和结果。回调不会记录在任何地方。
  • 如果您在结果尚未可用时调用 onComplete,回调将添加到“监听器”列表中。
  • 当结果可用时(有人在 promise 上调用 complete),然后安排所有监听器运行该结果,并删除监听器列表(内部状态更改为“已完成”有了这个结果")

这意味着您的回调链只会在“上游 future ”不完整之前建立。之后,一切都得到解决并被垃圾收集。


上面的“list of listeners”有点简化。需要特别注意的是,这些监听器不会最终相互引用,特别是要打破引用循环,在递归构建 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.

关于Scala Future `.onComplete` 函数在调用后被丢弃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56822179/

相关文章:

python - gRPC Python thread_pool 与 max_concurrent_rpcs

python - mysql 连接与 python 中的并发.futures 不能很好地配合

python - 如何在Python中使用concurrent.futures

scala - 计算列表中的数字在 Scala 中的元组间隔列表中出现的次数

scala - 创建 Scala 函数而不显式声明类型

scala - 在集合类型中对当前极值进行评分的最佳方法

python - Flask - 作业不作为后台进程运行

scala - 从 Future[ List[ A ] ] 获取 head Future 的首选方式

java - 在 Scala 中解析具有 ISO 格式的日期时间

python - Arrayfire python支持多GPU编程吗