weak_hash
A Weak Hash is a hash that stores references to objects while retaining the garbage collector’s ability to reclaim the object.
The API is similar to that of a Hash:
object = Object.new
wh = WeakHash.new
wh["value"] = object
wh["value"] # => object
object = nil
wh["value"] # => object (if garbage collector has not collected the object yet)
GC.start; GC.start # very probable that the object is collected now.
wh["value"] # => nil
Credits
This gem is based on two blog posts by Mauricio Fernández, including code by him and Robert Klemme:
I wrapped this on a gem for convenience, replaced a Thread.critical call on SimpleWeakHash with a mutex (for making it work with 1.9) and added some very simple specs.
Note on Patches/Pull Requests
-
Fork the project.
-
Make your feature addition or bug fix.
-
Add tests for it. This is important so I don’t break it in a future version unintentionally.
-
Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
-
Send me a pull request. Bonus points for topic branches.
Copyright
Copyright © 2010 Emmanuel Oga. See LICENSE for details.