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. This implementation does not pollute the global namespace.

Instance Method Summary collapse

Constructor Details

#initializeFiberLocals



7
8
9
10
# File 'lib/support_table_cache/fiber_locals.rb', line 7

def initialize
  @mutex = Mutex.new
  @locals = {}
end

Instance Method Details

#[](key) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/support_table_cache/fiber_locals.rb', line 12

def [](key)
  fiber_locals = nil
  @mutex.synchronize do
    fiber_locals = @locals[Fiber.current.object_id]
  end
  return nil if fiber_locals.nil?

  fiber_locals[key]
end

#with(key, value) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/support_table_cache/fiber_locals.rb', line 22

def with(key, value)
  fiber_id = Fiber.current.object_id
  fiber_locals = nil
  previous_value = nil
  inited_vars = false

  begin
    @mutex.synchronize do
      fiber_locals = @locals[fiber_id]
      if fiber_locals.nil?
        fiber_locals = {}
        @locals[fiber_id] = fiber_locals
        inited_vars = true
      end
    end

    previous_value = fiber_locals[key]
    fiber_locals[key] = value

    yield
  ensure
    if inited_vars
      @mutex.synchronize do
        @locals.delete(fiber_id)
      end
    else
      fiber_locals[key] = previous_value
    end
  end
end