3

Does anything special happen to objects when there are no variables pointing to them any more? Apart from being eligible for garbage collection, that is.

For example, currently, IO objects automatically close when they're garbage collected, if they haven't done so already. Even if you wanted to change this behavior, there isn't any way of changing it so that automatic closing occurs when no more variables point at the object, is there?

(My question is a slight simplification: WeakRef allows variables to point to objects and for them to be targets of garbage collection. Also, it's possible to access objects that don't have any variables pointing to them, for some implementations of Ruby, by using ObjectSpace. And regarding IO objects, there's things like IO.open(&block) that automatically close IO objects after the block has been executed.)

sawa
  • 165,429
  • 45
  • 277
  • 381
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
  • My question in return is, is there a problem you're addressing or is this academic/curiosity? I'd like to see some code examples showing the problem/curiosity. – the Tin Man Nov 29 '12 at 02:20
  • You can turn off GC if you want. – Boris Stitnicky Nov 29 '12 at 02:22
  • @theTinMan I was trying to answer a comment at http://stackoverflow.com/questions/764134/rubys-yield-feature-in-relation-to-computer-science/764862#comment18672522_764862 , and I was only 95% sure of my response to the comment. – Andrew Grimm Nov 29 '12 at 02:23

1 Answers1

1

No, there's no hook or special method that gets executed when there are no more references to an object.

The specific cases you mention are:

  • automatic closing of resources on garbage collection: this is achieved with a finalizer

  • automatic closing of resources at the end of a block: no magic here

    class IO
      def self.open(*args)
        yield file_handle = new(*args)
      ensure
        file_handle.close
      end
    end
    
  • WeakRef: there is magic here :-) In YARV, lib/weakref.rb uses ::ObjectSpace::WeakMap, which provides the weak reference semantics. JRuby implements WeakMap using Java's native weak reference semantics. IOW: this cannot actually be expressed in Ruby, it has to be provided by the runtime system.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653