Class: RedisReadWriteLocks::BaseLock

Inherits:
Object
  • Object
show all
Defined in:
lib/redis_read_write_locks/base_lock.rb

Direct Known Subclasses

ReadLock, WriteLock

Constant Summary collapse

DEFAULT_TTL =
30_000
DEFAULT_RETRY_DELAY =
100

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(redis:, name:, ttl: DEFAULT_TTL) ⇒ BaseLock

Returns a new instance of BaseLock.



10
11
12
13
14
15
16
# File 'lib/redis_read_write_locks/base_lock.rb', line 10

def initialize(redis:, name:, ttl: DEFAULT_TTL)
  @redis = redis
  @name = name
  @ttl = ttl
  @token = SecureRandom.uuid
  @acquired = false
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/redis_read_write_locks/base_lock.rb', line 8

def name
  @name
end

#tokenObject (readonly)

Returns the value of attribute token.



8
9
10
# File 'lib/redis_read_write_locks/base_lock.rb', line 8

def token
  @token
end

Instance Method Details

#acquire(retry_count: nil, retry_delay: DEFAULT_RETRY_DELAY) ⇒ Object

Raises:



22
23
24
25
26
27
28
29
30
31
# File 'lib/redis_read_write_locks/base_lock.rb', line 22

def acquire(retry_count: nil, retry_delay: DEFAULT_RETRY_DELAY)
  return try_acquire if retry_count.nil?

  return true if try_acquire
  retry_count.times do
    sleep retry_delay / 1000.0
    return true if try_acquire
  end
  raise LockTimeoutError, "Could not acquire #{lock_type} lock '#{@name}' after #{retry_count} retries"
end

#acquired?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/redis_read_write_locks/base_lock.rb', line 18

def acquired?
  @acquired
end

#synchronize(retry_count: nil, retry_delay: DEFAULT_RETRY_DELAY, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/redis_read_write_locks/base_lock.rb', line 33

def synchronize(retry_count: nil, retry_delay: DEFAULT_RETRY_DELAY, &block)
  if retry_count
    acquire(retry_count: retry_count, retry_delay: retry_delay)
  else
    acquire || raise(LockNotAcquiredError, "Could not acquire #{lock_type} lock '#{@name}'")
  end
  begin
    block.call
  ensure
    release
  end
end