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.47.0 lib/roda/cache.rb
roda-3.46.0 lib/roda/cache.rb
roda-3.45.0 lib/roda/cache.rb
roda-3.44.0 lib/roda/cache.rb
roda-3.43.1 lib/roda/cache.rb
roda-3.43.0 lib/roda/cache.rb
roda-3.42.0 lib/roda/cache.rb
roda-3.41.0 lib/roda/cache.rb
roda-3.40.0 lib/roda/cache.rb