Class: Concurrent::FiberLocalVar
| Relationships & Source Files | |
| Inherits: | Object |
| Defined in: | lib/concurrent-ruby/concurrent/atomic/fiber_local_var.rb |
Overview
A FiberLocalVar is a variable where the value is different for each fiber. Each variable may have a default value, but when you modify the variable only the current fiber will ever see that change.
This is similar to Ruby’s built-in fiber-local variables (‘Thread.current`), but with these major advantages:
-
FiberLocalVarhas its own identity, it doesn’t need a Symbol. -
Each Ruby’s built-in fiber-local variable leaks some memory forever (it’s a Symbol held forever on the fiber), so it’s only OK to create a small amount of them.
FiberLocalVarhas no such issue and it is fine to create many of them. -
Ruby’s built-in fiber-local variables leak forever the value set on each fiber (unless set to nil explicitly).
FiberLocalVarautomatically removes the mapping for each fiber once theFiberLocalVarinstance is GC’d.
Constant Summary
Class Method Summary
-
.new(default = nil, &default_block) ⇒ FiberLocalVar
constructor
Creates a fiber local variable.
Instance Attribute Summary
-
#value ⇒ Object
rw
Returns the value in the current fiber’s copy of this fiber-local variable.
-
#value=(value) ⇒ Object
rw
Sets the current fiber’s copy of this fiber-local variable to the specified value.
Instance Method Summary
-
#bind(value) { ... } ⇒ Object
Bind the given value to fiber local storage during execution of the given block.
- #default private
Constructor Details
.new(default = nil, &default_block) ⇒ FiberLocalVar
Creates a fiber local variable.
# File 'lib/concurrent-ruby/concurrent/atomic/fiber_local_var.rb', line 49
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
Instance Attribute Details
#value ⇒ Object (rw)
Returns the value in the current fiber’s copy of this fiber-local variable.
#value=(value) ⇒ Object (rw)
Sets the current fiber’s copy of this fiber-local variable to the specified value.
Instance Method Details
#bind(value) { ... } ⇒ Object
Bind the given value to fiber local storage during execution of the given block.
#default (private)
[ GitHub ]# File 'lib/concurrent-ruby/concurrent/atomic/fiber_local_var.rb', line 101
def default if @default_block self.value = @default_block.call else @default end end