Skip to content

Instantly share code, notes, and snippets.

@dantswain
Created April 7, 2015 15:30
Show Gist options
  • Save dantswain/c1198e27f95664449fec to your computer and use it in GitHub Desktop.
Save dantswain/c1198e27f95664449fec to your computer and use it in GitHub Desktop.
Ruby GC and finalizers
# encoding: utf-8
class Bar
def initialize(name)
@name = name
end
def hi
puts "HI #{@name}"
end
end
class Foo
def initialize(bar)
@bar = bar
end
def hi
@bar.hi
end
end
module Baz
def self.make_foo
bar = Bar.new('kept')
ObjectSpace.define_finalizer(bar, Baz.killed_a_bar('kept'))
Foo.new(bar)
end
def self.do_bar
bar = Bar.new('ephemeral')
bar.hi
ObjectSpace.define_finalizer(bar, Baz.killed_a_bar('ephemeral'))
nil
end
def self.killed_a_bar(name)
proc { puts "#{name} DIED"}
end
end
Baz.do_bar
foo = Baz.make_foo
foo.hi
puts 'DOING GC'
GC.start
puts 'GC DONE'
sleep(1)
foo.hi
### OUTPUT
#$ ruby gc_test.rb
#HI ephemeral
#HI kept
#DOING GC
#ephemeral DIED
#GC DONE
#HI kept
#kept DIED
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment