On 5/16/05, Eustaquio Rangel de Oliveira Jr. <eustaquiorangel / yahoo.com> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> Hello there!
> 
> I have this program:
> 
> - -------------------------------------------------------------------------
> class Car
>         attr_reader :number
>         def initialize(n)
>                 @number=n
>                 puts "Creating car no. #{n}:#{object_id}"
>         end
>         def to_s
>                 "Car no. #{@number}"
>         end
> end
> 
> def makeCar(n)
>         c = Car.new(n)
> end
> 
> def listCars
>         puts "\nListing cars:"
>         ObjectSpace.each_object(Car) {|o| puts "#{o}:#{o.object_id}"}
>         puts
> end
> 
> c1 = makeCar(1)
> makeCar(2)
> makeCar(3)
> 
> listCars()
> makeCar(4)
> makeCar(5)
> 
> listCars();
> 
> puts "Firing gc."
> GC.start
> listCars();
> - -------------------------------------------------------------------------
> 
> When I run, I get:
> 
> Creating car no. 1:-604870360
> Creating car no. 2:-604870370
> Creating car no. 3:-604870410
> 
> Listing cars:
> Car no. 3:-604870410
> Car no. 2:-604870370
> Car no. 1:-604870360
> 
> Creating car no. 4:-604870500
> Creating car no. 5:-604870490
> 
> Listing cars:
> Car no. 4:-604870500
> Car no. 5:-604870490
> Car no. 3:-604870410
> Car no. 2:-604870370
> Car no. 1:-604870360
> 
> Firing gc.
> 
> Listing cars:
> Car no. 4:-604870500
> Car no. 1:-604870360
> 
> My doubt is why Car no. 4 is still there, after running gc. There is no
> reference to it outside the function, right? So it should not have be
> sweeped by GC?
> 
> Thanks!
> 
> - ----------------------------
> EustŠ“uio "TaQ" Rangel
> eustaquiorangel / yahoo.com
> http://beam.to/taq
> UsuŠ”io GNU/Linux no. 224050
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.2.7 (GNU/Linux)
> 
> iD8DBQFCiO4mb6UiZnhJiLsRAmJ7AJ9M8a1CsY/ksAW1fThdmIpeLbB7gwCcCz5w
> +sh/g0F1Vork+DKH/xRj+9M=
> =Tm+7
> -----END PGP SIGNATURE-----
> 
> 

You script returns the expected result for me (only car 1).  WinXP, Ruby 1.8.2.

I'm guessing garbage collection is happening asynchronously, and that
your listCars executed before car 4 was collected?  Try sleep(2) in
between GC.start and listCars to see if that changes the result.

This is only a guess, and could be very wrong.  I have not looked at
the Ruby source to verify how garbage collection works.


Jason