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.



63
64
65
66
# File 'lib/tool/thread_local.rb', line 63

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