Class: Sync::SingleFlight

Inherits:
Object
  • Object
show all
Defined in:
lib/sync/singleflight.rb

Defined Under Namespace

Classes: Call

Instance Method Summary collapse

Constructor Details

#initializeSingleFlight



7
8
9
10
# File 'lib/sync/singleflight.rb', line 7

def initialize
  # Initialize a thread-safe map to store ongoing calls
  @calls = Concurrent::Map.new
end

Instance Method Details

#execute(key) { ... } ⇒ Object

Executes a block of code associated with a given key. Ensures that only one execution happens for the same key at a time.

Yields:

  • the block of code to be executed



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/sync/singleflight.rb', line 16

def execute(key)
  # Retrieve the call associated with the key
  call = @calls[key]
  if call.nil?
    # If no call exists, create a new one
    call = Call.new
    other = @calls.put_if_absent(key, call)
    if other.nil?
      begin
        # Execute the block and return the result
        return call.exec { yield }
      ensure
        # Ensure the call is removed from the map after execution
        @calls.delete(key)
      end
    else
      # If another call was added concurrently, use that one
      call = other
    end
  end
  # Wait for the existing call to complete and return its result
  call.await
end