From: Brian Candler Date: 2008-09-19T16:49:15+09:00 Subject: Re: Garbage collecting threads? David Masover wrote: >> The finalizer is only called *after* >> the farmer has been destroyed, so you can't use any methods or instance >> variables on it. > > However, wouldn't it be scoped? I could as easily set a local variable > when I > create the finalizer, right? Yes, as long as the local variable (bound into the finalizer) refers to objects held by the farmer, not the farmer itself. Otherwise the existence of the finalizer holding a reference to the farmer will in itself prevent the farmer from being garbage collected, so the finalizer can never be called. I started a separate thread about why garbage collection isn't happening in this case: http://www.ruby-forum.com/topic/165961 It's looking suspiciously like a bug in ruby-1.8, since apparently ruby-1.9 behaves as expected. But there's been no comment so far from an expert in Ruby internals. > Still doesn't answer the other part I need: Weak references. /usr/lib/ruby/1.8/weakref.rb :-) > I need to > know > exactly how I can use them, and how I can't -- what might be dangerous > about > them, for example. I can't see any particular pitfalls. But equally I can't see any reason why you want weak refs in this example. > Looking at your example, your workers still have references to your > queue and > to the farmer, which means the farmer will never be collected. I don't think you understand. If A holds a reference to B, then that may(*) prevent B from being garbage-collected, but it definitely doesn't prevent A from being garbage-collected. So, as long as the farmer exists, then the workers and the queue will exist. If no-one holds a reference to the farmer, then the farmer will be GC'd. Then if there no references to the worker or queue, other than those which were held by the farmer, then the worker or queue also will be garbage-collected. This is normal behaviour of a "normal" reference from farmer to worker/queue, not a weak ref. Regards, Brian. (*) I say "may" because Ruby's garbage collector is mark-and-sweep. If there is a isolated graph of objects, i.e. the only references to these objects are from other objects within this graph, then none of them will get marked, and so they'll all get swept at once. So in this case, the farmer and the workers may be GC'd at the same time, even though the farmer holds references to the workers. -- Posted via http://www.ruby-forum.com/.