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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With