Class: Tool::ThreadLocal

Inherits:
Delegator
  • Object
show all
Defined in:
lib/tool/thread_local.rb

Overview

Have thread local values without them actually being thread global.

Advantages:

  • values for all threads are garbage collected when ThreadLocal instance is

  • values for specific thread are garbage collected when thread is

  • no hidden global state

  • supports other data types besides hashes.

Examples:

To replace Thread.current hash access

local = Tool::ThreadLocal.new
local[:key] = "value"

Thread.new do
  local[:key] = "other value"
  puts local[:key] # other value
end.join

puts local[:key] # value

Usage with Array

local = Tool::ThreadLocal.new([:foo])
local << :bar

Thread.new { p local }.join # [:foo]
p local # [:foo, :bar]

Instance Method Summary collapse

Constructor Details

#initialize(default = {}) ⇒ ThreadLocal

Returns a new instance of ThreadLocal.



32
33
34
35
36
# File 'lib/tool/thread_local.rb', line 32

def initialize(default = {})
  @mutex = Mutex.new
  @default = default.dup
  @map = {}
end