Sha256: 0d224da76102be5ecb1965daaa3ea6cca7c5cb28379185ff598fb135f1832d74

Contents?: true

Size: 995 Bytes

Versions: 4

Compression:

Stored size: 995 Bytes

Contents

module CacheAdvance
  class Lock

    class LockAcquisitionFailureException < Exception; end
    
    DEFAULT_RETRIES = 5
    DEFAULT_EXPIRATION_TIME = 30

    def initialize(store)
      @store = store
    end
    
    def execute_locked(key, lock_expiry = DEFAULT_EXPIRATION_TIME, retries = DEFAULT_RETRIES)
      begin
        acquire(key, lock_expiry, retries)
        yield
      ensure
        release_lock(key)
      end
    end
    
    def acquire(key, lock_expiry = DEFAULT_EXPIRATION_TIME, retries = DEFAULT_RETRIES)
      retries.times do |count|
        begin
          return if @store.set("lock/#{key}", Process.pid, lock_expiry) == "STORED\r\n"
        end
        exponential_sleep(count) unless count == retries - 1
      end
      raise LockAcquisitionFailureException, "Couldn't acquire memcache lock for: #{key}"
    end

    def release_lock(key)
      @store.delete("lock/#{key}")
    end

    def exponential_sleep(count)
      sleep((2**count) / 10.0)
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
aub-cache_advance-1.1.2 lib/cache_advance/lock.rb
aub-cache_advance-1.1.3 lib/cache_advance/lock.rb
cache_advance-1.1.5 lib/cache_advance/lock.rb
cache_advance-1.1.4 lib/cache_advance/lock.rb