From: Robert Klemme Date: 2003-08-11T21:56:44+09:00 Subject: Re: WeakRef and caches "Tim Bates" schrieb im Newsbeitrag news:20030809012045.GA14728@bates.id.au... > Unfortunately, this doesn't work. The idea is that the cache always > returns strong-refs, so that the user doesn't have to worry about them > getting garbage-collected - to the user, they're just ordinary objects. > However, once they go outside the user's scope, the only reference to > them left is the weakref in the cache, and they can be garbage > collected. Then, if the user requests it again, it can be returned if > it's not GC'd yet, or regenerated and returned if it has. > > It seems, though, that the WeakRef implementation is such that if you > refer to an object other than via its weakref, the weakref-ness is > destroyed and the object never gets GC'd. Can anyone explain why and/or > offer a way around this? 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 def doit(arg) obj = @cache[@id] obj.mathod1 obj.mathod2 obj.mathod3(arg) # obj cleared here end Regards robert PS: There's a nice article about Java reference types which are quite similar: http://developer.java.sun.com/developer/technicalArticles/ALT/RefObj/