Ruby强制垃圾收集未按预期工作 [英] Ruby forcing garbage collection not working as expected

查看:49
本文介绍了Ruby强制垃圾收集未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中:

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?

The finalizer here is never called and there is no output. I would have expected the garbage collector to collect ex since it has been dereferenced. Why is GC.start not forcing ex to be collected and causing the finalizer to be called immediately?

推荐答案

我相信,当您创建新的 内核 )

I believe that when you create a new Proc (proc just calls Proc.new, in Kernel)

创建一个绑定到当前上下文的新Proc对象.

Creates a new Proc object, bound to the current context.

表示它正在保存对 self 对象的引用,因此永远不会取消引用以使垃圾收集器收集该对象.您应该改为在类方法内创建 proc ,以便上下文成为类而不是您要破坏的实例.

Means that it's saving a reference to the self object and thus can never be de-referenced for the garbage collector to collect it. You should create the proc inside a class method instead so that the context becomes the class not the instance you're trying to destroy.

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

这篇关于Ruby强制垃圾收集未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆