Class: Concurrent::AbstractThreadLocalVar

Inherits:
Object
  • Object
show all
Defined in:
lib/concurrent/atomic/thread_local_var.rb

Overview

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.

Examples:

v = ThreadLocalVar.new(14)
v.value #=> 14
v.value = 2
v.value #=> 2
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

Direct Known Subclasses

ThreadLocalVar

Defined Under Namespace

Modules: ThreadLocalJavaStorage, ThreadLocalRubyStorage

Constant Summary collapse

NIL_SENTINEL =
Object.new

Instance Method Summary collapse

Constructor Details

#initialize(default = nil) ⇒ AbstractThreadLocalVar

Returns a new instance of AbstractThreadLocalVar.



85
86
87
88
# File 'lib/concurrent/atomic/thread_local_var.rb', line 85

def initialize(default = nil)
  @default = default
  allocate_storage
end

Instance Method Details

#bind(value, &block) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
# File 'lib/concurrent/atomic/thread_local_var.rb', line 106

def bind(value, &block)
  if value.nil?
    stored_value = NIL_SENTINEL
  else
    stored_value = value
  end

  set stored_value, &block

  value
end

#valueObject



90
91
92
93
94
95
96
97
98
99
100
# File 'lib/concurrent/atomic/thread_local_var.rb', line 90

def value
  value = get

  if value.nil?
    @default
  elsif value == NIL_SENTINEL
    nil
  else
    value
  end
end

#value=(value) ⇒ Object



102
103
104
# File 'lib/concurrent/atomic/thread_local_var.rb', line 102

def value=(value)
  bind value
end