Sha256: edb28814aa83bca1b34c180410af058142335137c464086bdc63d9f752841a42

Contents?: true

Size: 807 Bytes

Versions: 13

Compression:

Stored size: 807 Bytes

Contents

# frozen-string-literal: true

require "thread"

class Roda
  # A thread safe cache class, offering only #[] and #[]= methods,
  # each protected by a mutex.
  class RodaCache
    # Create a new thread safe cache.
    def initialize
      @mutex = Mutex.new
      @hash = {}
    end

    # Make getting value from underlying hash thread safe.
    def [](key)
      @mutex.synchronize{@hash[key]}
    end

    # Make setting value in underlying hash thread safe.
    def []=(key, value)
      @mutex.synchronize{@hash[key] = value}
    end

    private

    # Create a copy of the cache with a separate mutex.
    def initialize_copy(other)
      @mutex = Mutex.new
      other.instance_variable_get(:@mutex).synchronize do
        @hash = other.instance_variable_get(:@hash).dup
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
roda-3.39.0 lib/roda/cache.rb
roda-3.38.0 lib/roda/cache.rb
roda-3.37.0 lib/roda/cache.rb
roda-3.36.0 lib/roda/cache.rb
roda-3.35.0 lib/roda/cache.rb
roda-3.34.0 lib/roda/cache.rb
roda-3.33.0 lib/roda/cache.rb
roda-3.32.0 lib/roda/cache.rb
roda-3.31.0 lib/roda/cache.rb
roda-3.30.0 lib/roda/cache.rb
roda-3.29.0 lib/roda/cache.rb
roda-3.28.0 lib/roda/cache.rb
roda-3.27.0 lib/roda/cache.rb