class Concurrent::ThreadLocalVar

v.value #=> 14
end
v.value #=> 2
v.value = 2
v.value #=> 14
t2 = Thread.new do
end
v.value #=> 1
v.value = 1
v.value #=> 14
t1 = Thread.new do
v = ThreadLocalVar.new(14)
@example
v.value #=> 2
v.value = 2
v.value #=> 14
v = ThreadLocalVar.new(14)
@example
@!macro thread_safe_variable_comparison
`ThreadLocalVar` automatically removes the mapping for each thread once the ‘ThreadLocalVar` instance is GC’d.
* Ruby’s built-in thread-local variables leak forever the value set on each thread (unless set to nil explicitly).
‘ThreadLocalVar` has no such issue and it is fine to create many of them.
so it’s only OK to create a small amount of them.
* Each Ruby’s built-in thread-local variable leaks some memory forever (it’s a Symbol held forever on the thread),
* ‘ThreadLocalVar` has its own identity, it doesn’t need a Symbol.
but with these major advantages:
This is similar to Ruby’s built-in thread-local variables (‘Thread#thread_variable_get`),
the current thread will ever see that change.
Each variable may have a default value, but when you modify the variable only
A `ThreadLocalVar` is a variable where the value is different for each thread.

def bind(value)

Returns:
  • (Object) - the value

Other tags:
    Yield: - the operation to be performed with the bound variable

Parameters:
  • value (Object) -- the value to bind
def bind(value)
  if block_given?
    old_value = self.value
    self.value = value
    begin
      yield
    ensure
      self.value = old_value
    end
  end
end

def default

@!visibility private
def default
  if @default_block
    self.value = @default_block.call
  else
    @default
  end
end

def initialize(default = nil, &default_block)

Parameters:
  • default_block (Proc) -- Optional block that gets called to obtain the
  • default (Object) -- the default value when otherwise unset
def initialize(default = nil, &default_block)
  if default && block_given?
    raise ArgumentError, "Cannot use both value and block as default value"
  end
  if block_given?
    @default_block = default_block
    @default = nil
  else
    @default_block = nil
    @default = default
  end
  @index = LOCALS.next_index(self)
end

def value

Returns:
  • (Object) - the current value
def value
  LOCALS.fetch(@index) { default }
end

def value=(value)

Returns:
  • (Object) - the new value

Parameters:
  • value (Object) -- the value to set
def value=(value)
  LOCALS.set(@index, value)
end