1 # Weak Reference class that does not bother GCing.
6 # p foo.to_s # original's class
7 # foo = WeakRef.new(foo)
8 # p foo.to_s # should be same class
9 # ObjectSpace.garbage_collect
10 # p foo.to_s # should raise exception (recycled)
14 class WeakRef<Delegator
16 class RefError<StandardError
19 ID_MAP = {} # obj -> [ref,...]
20 ID_REV_MAP = {} # ref -> obj
22 __old_status = Thread.critical
23 Thread.critical = true
35 ID_MAP[rid].delete(id)
36 ID_MAP[rid] = nil if ID_MAP[rid].empty?
39 Thread.critical = __old_status
46 ObjectSpace.define_finalizer orig, @@final
47 ObjectSpace.define_finalizer self, @@final
48 __old_status = Thread.critical
50 Thread.critical = true
51 ID_MAP[@__id] = [] unless ID_MAP[@__id]
53 Thread.critical = __old_status
55 ID_MAP[@__id].push self.__id__
56 ID_REV_MAP[self.id] = @__id
61 raise RefError, "Illegal Reference - probably recycled", caller(2)
63 ObjectSpace._id2ref(@__id)
78 p foo.to_s # original's class
79 foo = WeakRef.new(foo)
80 p foo.to_s # should be same class
81 ObjectSpace.garbage_collect
82 p foo.to_s # should raise exception (recycled)