Skip to content

Instantly share code, notes, and snippets.

@zentourist
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save zentourist/d070f823ba59ff8c99f5 to your computer and use it in GitHub Desktop.

Select an option

Save zentourist/d070f823ba59ff8c99f5 to your computer and use it in GitHub Desktop.
Playing with the Ruby Garbage Collector
require "objspace"
class TestWithFinalizer
def self.finalizer
proc {|o_id| puts "Collected #{o_id}"}
end
def test
3.times.each_with_object(mark []) {|i,a|
a << mark({ i => i })
}
end
def mark(x)
ObjectSpace.define_finalizer(x, TestWithFinalizer.finalizer)
puts "Marked #{x.object_id} - #{x.class}"
x
end
end
# This is the confusing session. It consistently never collects the last reference until after I `exit`.
# I can also successfully get the object from the object_id via `ObjectSpace._id2ref()`
t = TestWithFinalizer.new
o = t.test; nil # follow with 'nil' or Pry stores the output ref
# Marked 18869680 - Array
# Marked 18869420 - Hash
# Marked 18869220 - Hash
# Marked 18869020 - Hash
o = nil
ObjectSpace.garbage_collect
# Collected 18869680
# Collected 18869420
# Collected 18869220
exit
# Collected 18869020
# This is the way I would expect it to behave.
t = TestWithFinalizer.new
o1 = t.test; nil
# Marked 22159300
# Marked 22159280
# Marked 22159260
# Marked 22159240
o2 = t.test; nil
# Marked 22268960
# Marked 22268940
# Marked 22268920
# Marked 22268900
o1 = nil
ObjectSpace.garbage_collect
# Collected 22159300
# Collected 22159280
# Collected 22159260
# Collected 22159240
o2 = nil
ObjectSpace.garbage_collect
# Collected 22268960
# Collected 22268940
# Collected 22268920
# Collected 22268900
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment