Ruby Findings

digging for gems

Object destruction

Posted by Art Green Fri, 07 Sep 2007 17:48:00 GMT

Ruby does not provide programmer defined destruction methods. In C++ you can define a method that is messaged when the object instance is destroyed. This method can perform clean-up operations such as deleting temporary files.

Ruby, however, destroys objects dynamically during a scheduled garbage collection. This means that, during a run, it is impossible to know when an object instance will be destroyed. This fact combined with the lack of a destruction method can create headaches when there is a need to clean-up during object destruction.

Since there is no direct support for a destructor method, you must call a custom function, or more specific a proc object, when the garbage collector is about to destroy the object. As stated before it is unpredictable when this occurs.

Also if such a finalizer object has a reference to the orignal object, this may prevent the original object to get garbage collected.

Because of this problem, the finalize method below is a class method and not a instance method. So if you need to free resources for an object, like closing a socket or killing a spawned subprocess, you should do it explicitly with the ObjectSpace class.

class MyClass
  def initialize
    ObjectSpace.define_finalizer(self,
     self.class.method(:finalize).to_proc)
  end

  def MyClass.finalize(id)
    puts "Object #{id} dying at #{Time.new}"
  end
end

# test code
3.times {
    MyClass.new
}
ObjectSpace.garbage_collect

Posted in | no comments | atom

Trackbacks

Use the following link to trackback from your own site:
http://www.rubyfindings.com/trackbacks?article_id=object-destruction&day=07&month=09&year=2007

Comments

Leave a response

Leave a comment


html>