Skip to content

Instantly share code, notes, and snippets.

@csexton
Created October 10, 2015 15:40
Show Gist options
  • Save csexton/8be3b7433f9de8d1a452 to your computer and use it in GitHub Desktop.
Save csexton/8be3b7433f9de8d1a452 to your computer and use it in GitHub Desktop.
class Foo
def initialize
ObjectSpace.define_finalizer(self, proc {|id| puts "Finalizer one on #{id}" })
end
end
f = Foo.new
f = nil
@davearonson
Copy link

This code:

class Foo

  @@last_num = 0

  def initialize
    @num = (@@last_num += 1)
    ObjectSpace.define_finalizer(self, self.class.finalize(@num))
  end

  def self.finalize(num)
    proc { puts "Finalized #{num}" }
  end

end

f = Foo.new  # num 1

f = 3
f = "foo"
f = Object
f = nil

puts "starting GC after setting to other values"
puts "  (ideally we'd see a finalizer now!)"

GC.start

f = Foo.new  # num 2

puts "starting GC after setting to a new Foo"

GC.start

puts "exiting"

yields this output for me:

starting GC after setting to other values
  (ideally we'd see a finalizer now!)
starting GC after setting to a new Foo
Finalized 1
exiting
Finalized 2

Does it do something different for you?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment