Search This Blog

Sunday, November 1, 2009

Python, WeakReference

The memory pointed by weak-reference can be free by garbage collector. So the memory pointed by weak-reference can be used by something else. In other words, when the last remaining reference are weak-reference, the garbage collector are free to destroy the memory they reference to.

On the contrary, if the memory is pointed by at least one strong-reference, unless the reference count reaches zero, the memory pointed by the reference will stay.

How is this useful? Think about caching an image. If we have a hashmap using "name" as key to reference the image. If we are done with the image, but forgot to kill the hashmap, these image will stay in memory. Because there are "strong" reference call "names" in the hashmap.

The consequence is that, if such a hashmap is reachable in our program (even if we don't use the hashmap and the actual images anymore), the program will always keep the memory of the actual images.

Using the key "name" in hashtable as weak reference, the garbage collector can therefore free the actual image for you. So if you keep the hashmap around(and never use it), the images are no longer there~ it also means, if later on you again use the hashmap, the images are not there anymore~ (then, it's a design problem, if you still need to use the cache image for so long, why use weak reference at the first place? :)


http://docs.python.org/library/weakref.html
http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html

No comments: