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
RETRY_INTERVAL =
0.01

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(timeout: nil) ⇒ Object

Non-blocking: returns true/false. With timeout: retries for timeout seconds, returns true or raises LockTimeoutError.



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

def acquire(timeout: nil)
  return try_acquire if timeout.nil?

  deadline = Time.now.to_f + timeout
  loop do
    return true if try_acquire
    raise LockTimeoutError, "Timeout acquiring #{lock_type} lock '#{@name}'" if Time.now.to_f >= deadline
    sleep RETRY_INTERVAL
  end
end

#acquired?Boolean

Returns:

  • (Boolean)


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

def acquired?
  @acquired
end

#synchronize(timeout: nil, &block) ⇒ Object

Acquires lock, yields, releases. Raises LockNotAcquiredError if non-blocking acquire fails.



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/redis_read_write_locks/base_lock.rb', line 36

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