在以下代码中:
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
?
答案 0 :(得分:2)
我相信当您创建新的Proc
时,proc
只需拨打Proc.new
Kernel
}
创建一个绑定到当前上下文的新Proc对象。
表示它正在保存对self
对象的引用,因此永远不能取消引用垃圾收集器来收集它。您应该在类方法中创建proc
,以便上下文成为类,而不是您想要销毁的实例。
class ExampleClass
def initialize
ObjectSpace.define_finalizer(self, self.class.finalize)
end
def self.finalize
proc { puts "dead" }
end
end
ex = ExampleClass.new
# needed to do something with the object as well, not sure why,
# but it won't work without this line either
puts "object id = #{ex.object_id}"
ex = nil
GC.start
while true
end
并输出
object id = 70223915005060
dead
^Cexample.rb:20:in `<main>': Interrupt