Forcing a GC run

M

Michael Neumann

Hi,

How can I force that the GC frees all unreferenced objects? Basically
what I want is:

x = Object.new
xoid = x.object_id
ObjectSpace.define_finalizer(x, proc { puts "recycled" })

x = nil
ObjectSpace.garbage_collect
puts "after GC"
p ObjectSpace._id2ref(xoid)

What I get is:

before GC
after GC
#<Object....>
recycled

Where I'd have expected:

before GC
recycled
after GC
-> exception RangeError

Any hints?

Regards,

Michael
 
M

Michael Neumann

Hi,

How can I force that the GC frees all unreferenced objects? Basically
what I want is:

x = Object.new
xoid = x.object_id
ObjectSpace.define_finalizer(x, proc { puts "recycled" })

x = nil

this one is missing of course:

puts "before GC"
ObjectSpace.garbage_collect
puts "after GC"
p ObjectSpace._id2ref(xoid)

Regards,

Michael
 
S

Simon Strandgaard

[snip]


I don't know if this helps you?


bash-2.05b$ ruby d.rb
before call
before GC
"string"
recycled
after GC
after call
bash-2.05b$ expand -t2 d.rb
def test
x = 'string'
ObjectSpace.define_finalizer(x, proc { puts "recycled" })
p x
x = nil
end
f = lambda {
puts "before GC"
xoid = test
GC.start
puts "after GC"
}
puts "before call"
f.call
GC.start
puts "after call"
bash-2.05b$
 
T

Tobias Peters

Michael said:
How can I force that the GC frees all unreferenced objects?

This is impossible, because ruby's GC is conservative.

You can only rely on all objects getting freed before a clean exit of
the interpreter.

Tobias
 
M

Michael Neumann

This is impossible, because ruby's GC is conservative.

You can only rely on all objects getting freed before a clean exit of
the interpreter.

Thanks. My problems are gone now.

Regards,

Michael
 
M

Michael Neumann

How exactly did that happen? I'm confused. :)

A finalizer was not invoked at life-time... ah, hard to explain, see
yourself:

def take_snapshot
snap = []
ObjectSpace.define_finalizer(snap, proc {
p "finalizer called"
})
return snap
end

# BE CAREFUL! Might freeze your computer!
loop do
p "snap"
take_snapshot
end

Memory consumption will grow towards infinity. Why? Probably because the
proc, as it's a closure, implicitly references the snap object, and as
such, snap will never be recycled.

Whereas the following works fine:

$fin = proc { p "finalizer called" }
def take_snapshot
snap = []
ObjectSpace.define_finalizer(snap, $fin)
return snap
end

loop do
p "snap"
take_snapshot
end

Regards,

Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top