On Aug 1, 10:53 pm, "Wolfgang N?dasi-donner" <ed.oda... / wonado.de>
wrote:
> Joshua Chia wrote:
> > The finalizer is not getting called in this code -- it just prints
> > 'exiting'.  What's wrong?  I'm running it on v1.8.6 on Windows Vista.
>
> > class A
> >   def initialize
> >      ObjectSpace.define_finalizer(self, proc{|id| puts "finalizing
> > #{id}"})
> >   end
> > end
> > a = A.new
> > a = nil
> > GC.start
> > sleep(5)
> > puts 'exiting'
>
> ..which means, that the object was not destroyed by the GC. I don't see
> any additional actual reference to the object and don't understand this.
>

There is actually a simple reason. Remember that you're passing a
block, ie. a closure, to define_finalizer. That closure holds on to
the stuff like self, which in this case is the object to be finalized.
Thus the finalizer code is actually keeping the object alive.

Use define_finalizer outside the object associates the block with a
context that does not contain the object to be finalized (once the
local is set to nil), so it's actually garbage, and the finalizer
runs.

This is the most common misstep when using finalizers, and they should
be avoided if at all possible, because remember, there is no guarantee
when a finalizer will run, or if it will even run at all.

 - Evan Phoenix // evan () fallingsnow [] net

> Wolfgang N?dasi-Donner
> --
> Posted viahttp://www.ruby-forum.com/.