Sha256: 927f73f595db358192748cfcb0752cefb85154ff7b541986219ebeaf7d11bd50

Contents?: true

Size: 1008 Bytes

Versions: 49

Compression:

Stored size: 1008 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

    # Return the frozen internal hash.  The internal hash can then
    # be accessed directly since it is frozen and there are no
    # thread safety issues.
    def freeze
      @hash.freeze
    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

49 entries across 49 versions & 1 rubygems

Version Path
roda-3.88.0 lib/roda/cache.rb
roda-3.87.0 lib/roda/cache.rb
roda-3.86.0 lib/roda/cache.rb
roda-3.85.0 lib/roda/cache.rb
roda-3.84.0 lib/roda/cache.rb
roda-3.83.0 lib/roda/cache.rb
roda-3.82.0 lib/roda/cache.rb
roda-3.81.0 lib/roda/cache.rb
roda-3.79.0 lib/roda/cache.rb
roda-3.78.0 lib/roda/cache.rb
roda-3.77.0 lib/roda/cache.rb
roda-3.76.0 lib/roda/cache.rb
roda-3.75.0 lib/roda/cache.rb
roda-3.74.0 lib/roda/cache.rb
roda-3.73.0 lib/roda/cache.rb
roda-3.72.0 lib/roda/cache.rb
roda-3.71.0 lib/roda/cache.rb
roda-3.70.0 lib/roda/cache.rb
roda-3.69.0 lib/roda/cache.rb
roda-3.68.0 lib/roda/cache.rb