# MRI GC never collects?

**URL:** <https://www.ruby-forum.com/t/mri-gc-never-collects/220631>\
**Category:** Ruby\
**Created:** [June 14, 2012, 10:00pm UTC](https://www.ruby-forum.com/t/mri-gc-never-collects/220631 "2012-06-14T22:00:21Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![aris](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/258eb7/32.png) [@aris](https://www.ruby-forum.com/u/aris)\
**Post date:** [June 14, 2012, 10:00pm UTC](https://www.ruby-forum.com/t/mri-gc-never-collects/220631/1 "2012-06-14T22:00:21Z")

</div>

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-

---

<div class="post-metadata">

**Author:** ![rogerdpack](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/45deac/32.png) [@rogerdpack](https://www.ruby-forum.com/u/rogerdpack)\
**Post date:** [June 14, 2012, 10:05pm UTC](https://www.ruby-forum.com/t/mri-gc-never-collects/220631/2 "2012-06-14T22:05:23Z")

</div>

> 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.

> **[The Trouble with Ruby Finalizers](http://www.mikeperham.com/2010/02/24/the-trouble-with-ruby-finalizers/)**
>
> I was test driving Devil, the developer’s image library, recently to see if it would work for us in a long-living daemon. Task #1 to that end is to verify the absence of memory leaks, which seem to be common in image libraries. It was almost...

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-
