Created
April 7, 2015 15:30
-
-
Save dantswain/c1198e27f95664449fec to your computer and use it in GitHub Desktop.
Ruby GC and finalizers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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