Class: Stupidedi::ThreadLocalHash

Inherits:
Object
  • Object
show all
Includes:
Inspect
Defined in:
lib/stupidedi/thread_local.rb

Overview

Examples:

class Counter
  delegate :current, :current=, :to => @threadlocal

  def counter(start)
    @threadlocal = ThreadLocalHash.new(:current => start)
  end
end

counter = Counter.new(50)

x = Thread.new { 200.times { counter.current += 1 }; counter.current }
y = Thread.new { 300.times { counter.current += 1 }; counter.current }

x.value         #=> 250
x.value         #=> 350
counter.current #=> 50

Instance Method Summary collapse

Methods included from Inspect

#inspect

Constructor Details

#initialize(defaults = {}) ⇒ ThreadLocalHash

Returns a new instance of ThreadLocalHash.



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
# File 'lib/stupidedi/thread_local.rb', line 89

def initialize(defaults = {})
  @defaults = defaults.clone
  @threads  = Hash.new
  @cleaner  = lambda {|key| @threads.delete_if{|(t,_),_| t == key }}

  defaults.keys.each do |name|
    case defaults[name]
    when Numeric, Symbol, nil
      # These are immutable values and can't be cloned
      instance_eval <<-RUBY
        def #{name}
          @threads.fetch([key, :#{name}]) do
            @defaults[:#{name}]
          end
        end
      RUBY
    else
      instance_eval <<-RUBY
        def #{name}
          @threads.fetch([key, :#{name}]) do
            finalizer(Thread.current)
            @threads[[key, :#{name}]] =
              @defaults[:#{name}].clone
          end
        end
      RUBY
    end

    instance_eval <<-RUBY
      def #{name}=(value)
        unless @threads.include?(key)
          finalizer(Thread.current)
        end

        @threads[[key, :#{name}]] = value
      end
    RUBY
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, value = (getter = true)) ⇒ Object (private)



161
162
163
164
165
166
167
168
169
170
171
# File 'lib/stupidedi/thread_local.rb', line 161

def method_missing(name, value = (getter = true))
  if getter
    self[name]
  else
    if name.to_s =~ /^(.+)=$/
      self[$1.to_sym] = value
    else
      super
    end
  end
end

Instance Method Details

#[](name) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/stupidedi/thread_local.rb', line 129

def [](name)
  @threads.fetch([Thread.current, name]) do
    case value = @defaults[name]
    when Numeric, Symbol, nil
      # These are immutable values and can't be cloned
      value
    else
      finalizer(Thread.current)
      @threads[[key, name]] = value.clone
    end
  end
end

#[]=(name, value) ⇒ Object



142
143
144
145
146
147
148
# File 'lib/stupidedi/thread_local.rb', line 142

def []=(name, value)
  unless @threads.include?(key)
    finalizer(Thread.current)
  end

  @threads[[key, name]] = value
end