Class: SupportTableCache::FiberLocals

Inherits:
Object
  • Object
show all
Defined in:
lib/support_table_cache/fiber_locals.rb

Overview

Utility class for managing fiber-local variables. All values are stored in a single hash inside the fiber's native local storage (Thread.current, which is fiber-local in Ruby) so the fiber-local namespace is not polluted with individual keys. Because the state lives on the fiber itself, it is garbage collected along with the fiber and cannot leak or be picked up by another fiber.

Instance Method Summary collapse

Constructor Details

#initializeFiberLocals

Returns a new instance of FiberLocals.



10
11
12
# File 'lib/support_table_cache/fiber_locals.rb', line 10

def initialize
  @locals_key = :"support_table_cache_locals_#{object_id}"
end

Instance Method Details

#[](key) ⇒ Object



14
15
16
17
# File 'lib/support_table_cache/fiber_locals.rb', line 14

def [](key)
  locals = Thread.current[@locals_key]
  locals[key] if locals
end

#with(key, value) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/support_table_cache/fiber_locals.rb', line 19

def with(key, value)
  locals = Thread.current[@locals_key]
  if locals.nil?
    locals = {}
    Thread.current[@locals_key] = locals
  end

  exists = locals.key?(key)
  previous_value = locals[key]
  locals[key] = value

  begin
    yield
  ensure
    if exists
      locals[key] = previous_value
    else
      locals.delete(key)
      Thread.current[@locals_key] = nil if locals.empty?
    end
  end
end