From: Tim Bates Date: 2003-08-11T22:12:37+09:00 Subject: Re: WeakRef and caches On Mon, Aug 11, 2003 at 09:56:44PM +0900, Robert Klemme wrote: > That's the expected behavior: the weakest element in the strongest path > determines the availability of an instance. So an instance won't be GC'ed > as long as there is at least one strong ref to it. This has to be so, in > order to not change the semantics of strong refs. If they could be cleared > out of nothing many programs would not work as expected any more. > > Your cache implementation is exactly as it should be, but the code outside > should only hold on to an instance as long as it is needed, typically a > method invocation's duration. The only thing the outside world should store > is the id, which is needed to access the instance via the cache. A typical > usage pattern looks like this Yes, except that it doesn't work: [tim@zaphod:3 ~/ruby]$ cat weakref_test.rb require 'weakref' o = Object.new q = o o = WeakRef.new(o) ObjectSpace.garbage_collect p o p q q = nil # o is now the only reference to the object. ObjectSpace.garbage_collect puts o [tim@zaphod:3 ~/ruby]$ ruby weakref_test.rb # # # [tim@zaphod:3 ~/ruby]$ The final "puts o" should give a RefError, and indeed it does if I remove the line 'p q': [tim@zaphod:3 ~/ruby 1]$ cat weakref_test.rb require 'weakref' o = Object.new q = o o = WeakRef.new(o) ObjectSpace.garbage_collect p o #p q q = nil # o is now the only reference to the object. ObjectSpace.garbage_collect puts o [tim@zaphod:3 ~/ruby]$ ruby weakref_test.rb # weakref_test.rb:11:in `puts': Illegal Reference - probably recycled (WeakRef::RefError) from weakref_test.rb:11 [tim@zaphod:3 ~/ruby 1]$ But it seems that doing anything with a strong reference to an object causes the weakref to stop functioning as expected. Why is this the case? Tim Bates -- tim@bates.id.au