1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00
ruby--ruby/lib/weakref.rb
matz 4c86e4a580 * lib/logger.rb: improves the amount of documentation that Rdoc
picks up when processing logger.rb by moving the require
  statement back before the comment block.  a patch from Hugh
  Sasse <hgs at dmu.ac.uk>.  [ruby-core:08422]


git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@10647 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
2006-07-31 06:31:38 +00:00

98 lines
2.6 KiB
Ruby

require "delegate"
# Weak Reference class that does not bother GCing. This allows the
# referenced object to be garbage collected as if nothing else is
# referring to it. Because Weakref inherits from Delegator it passes
# method calls to the object from which it was constructed, so it
# is of the same Duck Type.
#
# Usage:
# foo = Object.new
# foo = Object.new
# p foo.to_s # original's class
# foo = WeakRef.new(foo)
# p foo.to_s # should be same class
# ObjectSpace.garbage_collect
# p foo.to_s # should raise exception (recycled)
class WeakRef<Delegator
# RefError is raised if an object cannot be referenced by a WeakRef.
class RefError<StandardError
end
@@id_map = {} # obj -> [ref,...]
@@id_rev_map = {} # ref -> obj
@@final = lambda {|id|
printf "final: %p\n", id
__old_status = Thread.critical
Thread.critical = true
begin
rids = @@id_map[id]
if rids
for rid in rids
@@id_rev_map.delete(rid)
end
@@id_map.delete(id)
end
rid = @@id_rev_map[id]
if rid
@@id_rev_map.delete(id)
@@id_map[rid].delete(id)
@@id_map.delete(rid) if @@id_map[rid].empty?
end
ensure
Thread.critical = __old_status
end
}
# Create a new WeakRef from +orig+.
def initialize(orig)
@__id = orig.object_id
printf "orig: %p\n", @__id
ObjectSpace.define_finalizer orig, @@final
ObjectSpace.define_finalizer self, @@final
__old_status = Thread.critical
begin
Thread.critical = true
@@id_map[@__id] = [] unless @@id_map[@__id]
ensure
Thread.critical = __old_status
end
@@id_map[@__id].push self.object_id
@@id_rev_map[self.object_id] = @__id
super
end
# Return the object this WeakRef references. Raise
# RefError if this is impossible. The object is that
# to which method calls are delegated (see Delegator).
def __getobj__
unless @@id_rev_map[self.object_id] == @__id
Kernel::raise RefError, "Illegal Reference - probably recycled", Kernel::caller(2)
end
begin
ObjectSpace._id2ref(@__id)
rescue RangeError
Kernel::raise RefError, "Illegal Reference - probably recycled", Kernel::caller(2)
end
end
def __setobj__(obj)
end
# Determine if this Weakref still refers to anything.
def weakref_alive?
@@id_rev_map[self.object_id] == @__id
end
end
if __FILE__ == $0
# require 'thread'
foo = Object.new
p foo.to_s # original's class
foo = WeakRef.new(foo)
p foo.to_s # should be same class
ObjectSpace.garbage_collect
ObjectSpace.garbage_collect
p foo.to_s # should raise exception (recycled)
end