-
Notifications
You must be signed in to change notification settings - Fork 414
/
thread_local_var.rb
127 lines (101 loc) · 2.19 KB
/
thread_local_var.rb
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
module Concurrent
# @!macro [attach] abstract_thread_local_var
# A `ThreadLocalVar` is a variable where the value is different for each thread.
# Each variable may have a default value, but when you modify the variable only
# the current thread will ever see that change.
#
# @example
# v = ThreadLocalVar.new(14)
# v.value #=> 14
# v.value = 2
# v.value #=> 2
#
# @example
# v = ThreadLocalVar.new(14)
#
# t1 = Thread.new do
# v.value #=> 14
# v.value = 1
# v.value #=> 1
# end
#
# t2 = Thread.new do
# v.value #=> 14
# v.value = 2
# v.value #=> 2
# end
#
# v.value #=> 14
class AbstractThreadLocalVar
module ThreadLocalRubyStorage
protected
unless Concurrent.on_jruby?
require 'ref'
end
def allocate_storage
@storage = Ref::WeakKeyMap.new
end
def get
@storage[Thread.current]
end
def set(value, &block)
key = Thread.current
@storage[key] = value
if block_given?
begin
block.call
ensure
@storage.delete key
end
end
end
end
module ThreadLocalJavaStorage
protected
def allocate_storage
@var = java.lang.ThreadLocal.new
end
def get
@var.get
end
def set(value)
@var.set(value)
end
end
NIL_SENTINEL = Object.new
def initialize(default = nil)
@default = default
allocate_storage
end
def value
value = get
if value.nil?
@default
elsif value == NIL_SENTINEL
nil
else
value
end
end
def value=(value)
bind value
end
def bind(value, &block)
if value.nil?
stored_value = NIL_SENTINEL
else
stored_value = value
end
set stored_value, &block
value
end
end
# @!macro abstract_thread_local_var
class ThreadLocalVar < AbstractThreadLocalVar
if Concurrent.on_jruby?
include ThreadLocalJavaStorage
else
include ThreadLocalRubyStorage
end
end
end