【问题标题】:What happens when a Scala "Future" is garbage collected?当 Scala“Future”被垃圾收集时会发生什么?
【发布时间】:2011-03-14 15:43:26
【问题描述】:

假设我有一个Stream,计算起来相当昂贵。我可以通过编写类似的东西轻松创建一个“提前计算”的线程

import scala.actors.Futures._
val s = future { stream.size }

如果我随后丢弃对该Future 的引用,该线程会被垃圾收集器杀死吗?

【问题讨论】:

  • 没有。垃圾收集器永远不会杀死线程。计算可能会产生垃圾收集器不知道的副作用,换句话说,线程可能正在做一些垃圾收集器不知道的重要事情——因此它永远无法安全地停止线程。

标签: scala garbage-collection future


【解决方案1】:

没有。该线程属于调度程序。在任何情况下,调度程序都会引用未完成的 Future 主体(这发生在 a.start()),因此在完成之前不会被垃圾收集。

object Futures {

  /** Arranges for the asynchronous execution of `body`,
   *  returning a future representing the result.
   *
   *  @param  body the computation to be carried out asynchronously
   *  @return      the future representing the result of the
   *               computation
   */
  def future[T](body: => T): Future[T] = {
    val c = new Channel[T](Actor.self(DaemonScheduler))
    val a = new FutureActor[T](_.set(body), c)
    a.start()
    a
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 2014-08-08
    相关资源
    最近更新 更多