-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweakref.rb
More file actions
executable file
·64 lines (50 loc) · 1.01 KB
/
weakref.rb
File metadata and controls
executable file
·64 lines (50 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env ruby
#-*- coding: utf-8 -*-
class Person
def hello
puts "Hello, I'm #{self.object_id}"
end
end
class WeakRef
@@ids = {}
@@final = Proc.new{|id| # Defined here because closures
puts "finalizing: #{id}"
@@ids[id].reset!
@@ids.delete(id)
}
def initialize(target)
@target_id = target.object_id
@@ids[@target_id] = self
ObjectSpace.define_finalizer(target, @@final)
end
def reset!; @target_id = nil; end
def method_missing(sym, *args, &block)
begin
raise RangeError.new unless @target_id
ObjectSpace._id2ref(@target_id)
.send(sym, *args, &block)
rescue RangeError
raise 'TargetUnreachable' unless @target_id
end
end
end
require 'thread'
def test # Don't create blocks here, take care with closures
w = WeakRef.new(Person.new)
w.hello
GC.enable
GC.start
return w
end
Thread.exclusive do
begin
w1 = test
w2 = test
GC.enable
GC.start
w1.hello
w2.hello
rescue => e
puts e.inspect
end
end