MRI GC never collects?

With the following code:

def finalized_puts bad, benign
ObjectSpace.define_finalizer(bad) { puts benign.to_s }
end

n = 0
loop {
a = [3]
finalized_puts a, n

GC.start

n += 1
if n % 10000 == 0
print ‘.’
end
}

I’d “expect” that every so often it spits out some numbers, as objects
are collected (jruby does do it this way).

However with both
ruby 1.9.2p180 (2011-02-18) [i386-mingw32]
and
ruby 1.8.7 (2011-02-18 patchlevel 334) [i386-mingw32]

That code appears to just eat memory forever, and never run the
finalizers.

Am I missing anything here? Is it reproducible for y’all?
-roger-

That code appears to just eat memory forever, and never run the
finalizers.

Am I missing anything here? Is it reproducible for y’all?

Looks like I fell victim to the “never use a proc or block for a
finalizer” trick.

http://www.mikeperham.com/2010/02/24/the-trouble-with-ruby-finalizers/

The working version would be as follows:

def finalized_proc benign
proc { puts benign.to_s }
end

n = 0
loop {
a = [3]
ObjectSpace.define_finalizer(a, finalized_proc(n))
n += 1
if n % 10000 == 0
print ‘.’
end
}

Jruby must be pretty smart to be able to avoid this somehow.
-roger-

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs