[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Doubt about GC

Eric Mahurin

5/16/2005 8:39:00 PM

I'm also having troubles with garbage collection. The previous
code worked for me, but this modified version doesn't quite. I
still get 2 cars (#1 and old #4) in the end instead of 1 (#1).
In the code below, I put the car numbers and object_id's in a
class hash - kind of like weakref. It took me a little while
to figure out, but intially the finalizer proc was also causing
an object ref because I had it defined in initialize (created a
ref to a binding in the object - I think).

class Car
@@cars = Hash.new
Finalizer = proc { |id|
i = @@cars.index(id)
puts("Garbage car #{i}:#{id}")
@@cars.delete(i) if i
}
def initialize(n)
@number=n
puts "Creating #{self}"
@@cars[n] = object_id
ObjectSpace.define_finalizer(self,Finalizer)
end
def to_s
"Car no. #{@number}:#{object_id}"
end
def Car.listCars
puts "\nListing cars (from @@cars keys):"
@@cars.each_key { |n| puts "Car no. #{n}" }
puts "\nListing cars (from @@cars values):"
@@cars.each_value { |id| puts ObjectSpace._id2ref(id) }
puts "\nListing cars (from ObjectSpace):"
ObjectSpace.each_object(Car) {|o| puts o}
puts
end

end

c1 = Car.new(1)
Car.new(2)
Car.new(3)

Car.listCars()
Car.new(4)
Car.new(5)

Car.new(3)
Car.new(4)

Car.listCars();

puts "Firing gc."
GC.start
sleep(1)
Car.listCars();
sleep(1)
GC.start
sleep(1)
Car.listCars();




Yahoo! Mail
Stay connected, organized, and protected. Take the tour:
http://tour.mail.yahoo.com/mai...