views:

133

answers:

1

Say I have a Stream that's rather expensive to compute. I can easily create a thread that "computes ahead" just by writing something like

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

If I then throw away the reference to this Future, will that thread be killed off by the garbage collector?

+7  A: 

No. The thread belongs to the scheduler. In any case, the scheduler has a reference to the body un-finished Future (this happens in a.start()), so it won't be garbage collected before completion.

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
  }
}
retronym