【发布时间】:2017-07-18 19:24:53
【问题描述】:
在以下代码中:
class ExampleClass
def initialize
ObjectSpace.define_finalizer(self, proc{puts 'dead'})
end
end
ex = ExampleClass.new
ex = nil
GC.start
while true
# the while loop is to prevent the program from terminate
# if the program does terminate, the finalizer gets called in the end like expected
end
这里的终结器永远不会被调用,也没有输出。我本来希望垃圾收集器收集ex,因为它已被取消引用。为什么GC.start 不强制收集ex 并立即导致finalizer to be called?
【问题讨论】:
-
如果我使用 control+c 关闭您的代码以及将
while true end替换为exit,我会看到dead打印。我在 Ruby 2.5.0-dev fwiw 上。你在哪个平台上? -
我在 Eclipse 上使用 Ruby 2.4.0
-
哦,终结器在没有 GC.start 的情况下可以工作吗?
-
我想知道为什么当我调用
GC.start时dead不能正确打印。我在那里放了一个while循环来表明程序没有终止。
标签: ruby garbage-collection finalizer