Skip to content

Instantly share code, notes, and snippets.

Created December 13, 2012 16:46
Show Gist options
  • Save anonymous/4277829 to your computer and use it in GitHub Desktop.
Save anonymous/4277829 to your computer and use it in GitHub Desktop.
Ruby Garbage Collector not garbage collecting as expected
class Person
def self.destructor name
proc{ puts "I AM DYING: #{name}"}
end
attr_reader :name
def initialize name
@name = name
ObjectSpace.define_finalizer self, Person.destructor(name)
end
end
p = Person.new 'John'
p = nil
GC.start
# person 'John' is not garbage collected now, why?
Person.new 'Thomas'
GC.start
# I AM DYING: John # Person 'John' is garbage collected
@pithyless
Copy link

  1. There are no guarantees whatsoever that any GC run will collect particular unreachable instances.
  2. You can't rely on the GC calling your finalizers when the object is reaped. This is intentionally not defined to allow VM implementors maximum freedom for optimization.
  3. The only guarantee is that all finalizers are invoked eventually*, even if it is at process termination time.

[*] unless of course there is a SegFault :)

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