13
假設我有一個Stream
,計算起來相當昂貴。我可以輕鬆地創建一個線程,「計算進取」只是寫東西像當Scala「Future」被垃圾收集時會發生什麼?
import scala.actors.Futures._
val s = future { stream.size }
如果我再扔掉參照本Future
,將線程被垃圾收集器被殺死了嗎?
假設我有一個Stream
,計算起來相當昂貴。我可以輕鬆地創建一個線程,「計算進取」只是寫東西像當Scala「Future」被垃圾收集時會發生什麼?
import scala.actors.Futures._
val s = future { stream.size }
如果我再扔掉參照本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
}
}
不。垃圾回收器從不殺死線程。計算可能有垃圾收集器無法知道的副作用,換句話說,線程可能正在做一些垃圾收集器無法知道的重要事情 - 所以它無法安全地停止線程。 – Jesper 2010-07-12 07:12:49